Entity Framework: combining exact and wildcard searching conditional on search term

删除回忆录丶 提交于 2019-12-12 21:19:50

问题


I'm creating a query to search the db using EF. TdsDb being the EF context.

string searchValue = "Widget";
TdsDb tdsDb = new TdsDb();
IQueryable<Counterparty> counterparties;

I can do exact match:

counterparties = tdsDb.Counterparties.Where(x => x.CounterpartyName == searchValue);

or wildcard match:

counterparties = tdsDb.Counterparties.Where(x => x.CounterpartyName.Contains(searchValue));

But I want to be able to do both i.e. (psudo code)

counterparties = tdsDb.Counterparties.Where(x => 
          if (searchValue.EndsWith("%")) 
                 {
                      if (searchValue.StartsWith("%"))
                          {x.CounterpartyName.Contains(searchValue)}
                      else 
                          {x.CounterpartyName.StartsWith(searchValue)}
                 }   
          else
                 {x => x.CounterpartyName == searchValue}
      );

Now clearly I can't put an if statement in the where clause like that. But I also can't duplicate the queries: shown here they are hugely dumbed down. The production query is far longer, so having multiple versions of the same long query that vary on only one clause seems very unhealthy and unmaintainable.

Any ideas?


回答1:


You should be able to use the ternary operator:

bool startsWithWildCard = searchValue.StartsWith("%");
bool endsWithWildCard = searchValue.EndsWith("%");

counterparties = tdsDb.Counterparties.Where(x => 
      endsWithWildCard
          ? (startsWithWildCard
              ?  x.CounterpartyName.Contains(searchValue)
              : (x.CounterpartyName.StartsWith(searchValue)))
          : (x.CounterpartyName == searchValue));

Did you test btw if querying by a searchValue that has an % at the beginning or end works as you expect? It might be possible that % will be escaped as a character to query for because StartsWith and Contains will prepend/append % wildcards to the generated SQL search term anyway. In that case you need to cut off the % from the searchValue before you pass it into StartsWith or Contains.



来源:https://stackoverflow.com/questions/12517077/entity-framework-combining-exact-and-wildcard-searching-conditional-on-search-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!