假设我有以下域名(不是我的实际域名,而是一个简单的例子)
public class ClassRoom
{
public int Id {get;set;}
public string Name {get;set;}
public virtual ICollection<Desk> Desks{get;set;}
public virtual ICollection<LunchBox> LunchBoxs{get;set;}
}
public class Desk
{
public int Id {get;set;}
public String Colour {get;set;}
public String Make {get;set;}
Public ClassRoom ClassRoom {get;set;}
}
public class LunchBox
{
public int Id {get;set;}
public String Colour {get;set;}
public int Volume {get;set;}
}
我希望能够查询如下
“给我所有有蓝色办公桌或绿色午餐盒的课程”,返回班级列表
我原本认为代码是
var efClasses = (from d in myentity.ClassRooms
where ( (d.Desks.Colour == "blue")
|| (d.LunchBoxs.Colour == "green) )
select d).Distinct();
这样做会给我带来错误
无法将lambda表达式转换为类型'string',因为它不是委托类型 (显然对Color不满意,它希望这里有一个方法
所以我把它改成了这个实验
var efClasses = (from d in myentity.ClassRoom
where ( (d.Desks.Where(x=>x.Colour == "blue"))
|| (d.LunchBoxs.Where(x=>x.Colour == "green)) )
select d).Distinct();
但这也不会编译(事后我有一种感觉,我在试图运气。
我可以反过来改变我的myentity.Desks和myEntity.Lunchboxs,并返回两个单独的ClassRooms列表,然后找到联合,但这将需要2个单独的DB命中,并且感觉哈克
答案 0 :(得分:3)
而不是使用count&gt; 0,你可以使用Any
var efClasses = (from d in myentity.ClassRoom
where (d.Desks.Any(x => x.Colour == "blue") ||
d.LunchBoxs.Any(x => x.Colour == "green"))
select d);
答案 1 :(得分:0)
像这样使用Count&gt; 0。
var efClasses = (from d in myentity.ClassRoom
where (d.Desks.Count(x => x.Colour == "blue") > 0
|| d.LunchBoxs.Count(x => x.Colour == "green") > 0)
select d);