Linq include with where clause

2019-02-14 23:50发布

Hey so I've got the situation where I'm pulling a client back from the database and including all the case studies with it by way of an include

return (from c in db.Clients.Include("CaseStudies")
        where c.Id == clientId
        select c).First();

but what I want to do now is and a where clause on the included casestudies so that it only returns the case studies where deleted = false

sort of like this

return (from c in db.Clients.Include("CaseStudies")
        where c.Id == clientId
        && c.CaseStudy.Deleted == false
        select c).First();

But this doesn't work :( any ideas

3条回答
劫难
2楼-- · 2019-02-15 00:12

You can return a similar group of records this way, the GroupBy is going to make the enumeration different, but its not difficult.

CaseStudies.Include("Client")
           .Where(c => !c.Deleted && c.Client.ID == ClientID)
           .GroupBy(c => c.Client.ID);
查看更多
我命由我不由天
3楼-- · 2019-02-15 00:31

Conditional includes are not supported out-of-the-box in EF v1.0. But Alex James has a bit hacky workaround for that explained well here: http://blogs.msdn.com/alexj/archive/2009/10/13/tip-37-how-to-do-a-conditional-include.aspx

 var dbquery =
   from c in db.Clients
   where c.Id == clientID
   select new {
      client = c, 
      caseStudies = from cs in c.CaseStudy
                where cs.Deleted==false
                select cs
   };

return dbquery
   .AsEnumerable()
   .Select(c => c.client);

Also, I haven't succeeded to make this workaround work with many-to-many relationships.

查看更多
Luminary・发光体
4楼-- · 2019-02-15 00:33

One option is to perform a query on your results, like this:

var results = (from c in db.Clients.Include("CaseStudies")
               where c.Id == clientId
               select c).First();

results.CaseStudies = (from c in results.CaseStudies
                       where c.Deleted == false
                       select c).ToList();

Or of course you can use a lambda expression:

var results = db.Clients
                .Include(c => c.CaseStudies)
                .Where(c => c.ID == clientId).First();

results.CaseStudies = results.CaseStudies.Where(c => !c.Deleted).ToList();
查看更多
登录 后发表回答