Linq To Sql 'Where Or' operator

岁酱吖の 提交于 2019-12-18 12:28:51

问题


I need to create a query which checks if a field (string) contains one or more words supplied at run time.

Basically I need to be able to ask a WhereOr question. This seems like it should be a common issue when dealing with LinqToSql.

I found the following reference but can't make sense out of it - and have no idea how to use it in my project.

i've tried the following loop:

        var query = from d in context.Domains select d;
        for (int i = 0; i < words.Length; i++)
        {
            query = query.Where(d => d.Name.Contains(words[i]));
        }

but this builds a SQL query with WHERE AND Clauses NOT Where OR


回答1:


I use PredicateBuilder for such things.

The predicate construction looks like this:

     var query = from d in context.Domains select d;
     var predicate = PredicateBuilder<Domains>.False();

     for (int i = 0; i < words.Length; i++)
        {
            predicate = predicate.Or(d => d.Name.Contains(words[i]));
        }
    query = query.Where(predicate);


来源:https://stackoverflow.com/questions/1775050/linq-to-sql-where-or-operator

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