Thursday, April 28, 2011

Linq To Sql 'Where Or' operator

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

From stackoverflow
  • 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);
    
    RichardOD : +1. Yes, this is what I'd also recommend
    Harry : Wonder why this wasn't backed into LinqToSql

0 comments:

Post a Comment