EF4 LINQ - 在连接上添加过滤

时间:2011-03-28 17:29:31

标签: .net entity-framework-4 linq-to-entities

如何在LINQ中向JOIN TABLE ....添加FILTER CLAUSE?

  
    

AND t2.Public = 1 AND t2.Color ='Blue'

  

SELECT t1.ID, t1.Name, (SELECT COUNT(*) 
                      FROM tbl2 t2 
                     WHERE t2.ID = t1.ID 
                       AND t2.Public = 1 AND t2.Color = 'Blue') AS MyCount 
 FROM tbl1 t1
WHERE t1.State = 'CA'

2 个答案:

答案 0 :(得分:1)

看起来应该是这样的。

from t1 in context.tbl1
where t1.State = "CA"
select new 
{
    t1.ID, 
    t1.Name,
    MyCount = t1.tbl2s.Count(t2 => t2.Public && t2.Color == "Blue")
}

这是关于我可以提供的所有帮助,而不必更多地了解您的上下文中的实体的名称,它们之间的关系以及它们的标量值的类型。

答案 1 :(得分:1)

如果您的实体之间没有导航属性,请使用:

var data = from t1 in context.Tbl1
           join t2 in context.Tbl2 on t1.Id equals t2.Id
           where t1.State = "CA" && t2.Public == 1 && t2.Color = "Blue"
           group t1 by new { t1.Id, t1.Name } into g
           select new 
               {
                   Id = g.Key.Id,
                   Name = g.Key.Name,
                   Count = g.Count()
               };

如果他们有导航属性,请使用@StriplingWarrior提供的解决方案