2013-12-23 79 views
0

假設我有以下域(不是我的實際域名,但一個簡單的例子)根據過濾實體框架選擇對象進行的跨多個子集

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表達式到類型「串」,因爲它不是一個委託類型 (顯然不滿意的顏色,它期望在這裏的方法

所以我改變它作爲一個實驗

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

但是,這不會編譯(事後看來,我有一種感覺,我試圖在這個我的運氣。

我可以通過改變我的from myentity.Desks和myEntity.Lunchboxs,然後返回兩個ClassRooms的單獨列表,然後找到聯合,但這需要2個獨立的數據庫匹配,並且感覺哈克

回答

3

而不是使用計數> 0,你可以使用任何

var efClasses = (from d in myentity.ClassRoom 
       where (d.Desks.Any(x => x.Colour == "blue") || 
         d.LunchBoxs.Any(x => x.Colour == "green")) 
       select d); 
0

像這樣使用計數> 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);