Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic SQL Query Entity Framework

I searched though many posts on stack overflow to get me an answer but I am not clear yet. I am just looking for some simple way to build dynamic queries. I was able to do simple queries involving single expression in where clause but I am not able to find any easy way to handle multiple expressions. I have experience of working with NHibernate criteria API which is very handy for rapid and compile time safe query constructions. I though something similar will be available on EntityFramework but so far no luck. Is there any easy way beside manually building string queries? Have a look at following code I thought it should work but it doesn't. Actually it doesn't builds query upon multiple lambda expressions. I was expecting that each where call will add one AND expression to where clause. Am I missing something ?

var query = Entities.Current.Jobs.AsQueryable<Job>();

            if (!string.IsNullOrEmpty(keywords))
            {
                query.Where(j => j.Title.Contains(keywords) || j.Description.Contains(keywords));
            }

            if (industryId > 0)
            {
                query.Where(j => j.IndustryId == industryId);
            }

            if (countyId > 0)
            {
                query.Where(j => j.CountyId == countyId);
            }

            return query.ToList<Job>();
like image 561
Mazhar Qayyum Avatar asked Oct 16 '11 16:10

Mazhar Qayyum


1 Answers

IQueryable is immutable; you cannot (directly) modify the query of an existing IQueryable. query.Where returns a new IQueryable with an additional where clause.

You aren't doing anything with these new IQueryables.

You need to write

query = query.Where(...)
like image 116
SLaks Avatar answered Sep 27 '22 15:09

SLaks