LINQ to Entities - 跨关系查询和过滤

LINQ to Entities - query across relationships and filter

我很难用 LINQ 和 Lambda 表达式查询一组相关实体。

我有四个相关的实体...

车辆 1:n 车辆类型 n:1 价格 1:n 客户类型

我正在尝试获取给定车辆和客户类型的价格列表。例如,我想获取福特野马 (VehicleTypeId = 2) 的所有价格。在这些价格中,我想包括价格所属的客户类型(政府、商业、零售)。

我想我也许可以做到以下...

Prices.Include(p => p.VehicleTypes)
      .Include(p => p.CustomerTypes)
      .Where(p => p.VehicleTypes.Vehicles.Select(v => v.Id == 2)

但是我得到这个错误...

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<bool>' to 'bool'

我似乎无法创建一个 Where 条件,我可以在其中过滤要购买的车辆的 ID,同时在结果中包含 CustomerType。

编辑:只是想指出我已经包含 using System.Data.Entity 所以我可以访问类型安全的包含扩展

如果您需要那种车辆和特定客户类型的价格,您可以按如下方式过滤:

var prices= Prices.Include(p => p.VehicleTypes)
                  .Include(p => p.CustomerTypes)
                  .Where(p => p.VehicleTypes.Vehicles.Any(v => v.Id == 2)// With this condition you make sure that Mustang belong to this set of vehicles
                           && p.CustomerTypes.Type=="Commercial");

但如果您想过滤结果中的车辆,您将需要将查询投影到匿名类型或 DTO:

var query=  Prices.Include(p => p.VehicleTypes)
                  .Include(p => p.CustomerTypes)
                  .Where(p => p.VehicleTypes.Vehicles.Any(v => v.Id == 2)
                           && p.CustomerTypes.Type=="Commercial")
                  .Select(p=>new {CustomerType=p.CustomerTypes.Type, 
                                  Vehicles=p.VehicleTypes.Vehicles.Where(v => v.Id == 2)});