使用LINQ查找公共实体

本文关键字:实体 查找 LINQ 使用 | 更新日期: 2023-09-27 17:50:22

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

代码:

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

使用LINQ查找公共实体

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