猿问

获取具有满足特定条件的所有子项的实体

只是一个免责声明,这可能已经被问过了,但我真的不知道要搜索什么。


所以基本上我有以下模型:


public class Car

{

    public int Id { get; set; }


    public string UniqueName { get; set; }


    public List<Feature> Features { get; set; }

}


public class Feature

{

    public int Id { get; set; }


    public string Name { get; set; }


    public decimal Price { get; set; }

}

假设我想买一辆等于 的汽车,但价格低于 100 美元。UniqueNameBentleFeatures


我可以做这样的事情:


var car = DbContext.Cars.FirstOrDefault(x=> x.UniqueName == "Bentle");

car.Features = car.Features.Where(x=> x.Price <= 100).ToList();

这确实有效,但在我看来,这是很多不必要的转换。有什么方法可以缩短此查询?

一些要求:

  • 我需要实体本身Car

  • 仅包含成本低于 100 美元的列表FeaturesFeatures



慕田峪4524236
浏览 130回答 1
1回答

慕勒3428872

虽然我在您的查询中没有看到任何不必要的转换,但如果您想在一行中执行您的请求,您可以尝试以下操作:var car = DbContext.Cars.Where(x=> x.UniqueName == "Bentle").Select(car =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new Car()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Features = car.Features.Where(x=> x.Price <= 100),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; /*here copy the remaining properties of car object*/&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }).FirstOrDefault();
随时随地看视频慕课网APP
我要回答