2012-12-30 52 views
0

找到共同的實體我有持有fueltype也在另一個實體的汽車模型實體。他們有許多一對多的關係。使用LINQ

代碼:

public class CarModel 
{ 
    public int Id { get; set; } 
    public string Model { get; set; } 

    public ICollection<CarFuel> Fuel { get; set; } 
} 

public class CarFuel 
{ 
    public int Id { get; set; } 
    public string FuelType { get; set; } 

    public ICollection<CarModel> Model { get; set; } 
} 

int model = 2002; // this is coming from a selectbox 

var models = (from m in db.CarModels where m.Id == model select m).ToList(); 
var fuels = (from e in db.CarFuels select e).ToList(); 
var result = fuels.Where(p => models.Any(q => q.Fuel == p)).ToList(); // this doesn't work because it is looking for primitive types rather than entitites. 

所以,我想爲CarFuel查詢將呈現具有與spesific模型關係的結果只設置類型。所以我不想顯示與創建CarModel結果集,它沒有任何關係CarFuel。

回答

2
var fuels = db.CarFuels.Where(cf => cf.Model.Any(m => m.Id == model)) 
+1

感謝。有用! – MrGorki