简体   繁体   中英

Find the common entities by using LINQ

I have a car model entity which is holding fueltype also in another entity. they have a many-to-many relation.

code:

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.

So, I want to make a query for CarFuel which will present the types that have relations with the spesific models result set only. So I don't want to display any CarFuel which doesn't have relation with the created CarModel result set.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM