使用LINQ查找公共实体

时间:2012-12-30 13:43:28

标签: c# entity-framework linq-to-entities

我有一个汽车模型实体,它也在另一个实体中持有燃料类型。他们有多对多的关系。

代码:

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进行查询,它将显示仅与特定模型结果集有关系的类型。所以我不想显示任何与创建的CarModel结果集无关的CarFuel。

1 个答案:

答案 0 :(得分:2)

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