Linq包含where子句

时间:2009-11-05 14:19:14

标签: linq include where-clause

嘿,所以我遇到的情况是我从数据库中取回客户端并通过包含所有案例研究包括

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

但我现在想要做的是和所包含的casestudies的where子句,以便它只返回案例研究,其中deleted = false

有点像这样

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

但这不起作用:(任何想法

3 个答案:

答案 0 :(得分:7)

EF v1.0中不支持开箱即用的条件包含。但亚历克斯詹姆斯有一些hacky解决方法,因为这解释得很好: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);

此外,我还没有成功地使这种解决方法适用于多对多关系。

答案 1 :(得分:1)

您可以通过这种方式返回类似的记录组,GroupBy将使枚举不同,但并不困难。

CaseStudies.Include("Client")
           .Where(c => !c.Deleted && c.Client.ID == ClientID)
           .GroupBy(c => c.Client.ID);

答案 2 :(得分:0)

一种选择是对结果执行查询,如下所示:

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();

当然你可以使用lambda表达式:

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

results.CaseStudies = results.CaseStudies.Where(c => !c.Deleted).ToList();