我在我的EF项目中设置了TPT继承,其中包含一个超类型和两个子类型.我希望获得超类型的所有对象和Include()子类型的导航属性,以达到此效果(更改类名以保护befuddled):
var thelist = DataContext.Fleets .Include(x => x.Vehicles.Select(y => y.EngineData)) // Not specific to Car or Truck .Include(x => x.Vehicles.OfType<Car>().Select(y => y.BultinEntertainmentSystemData)) // Only Cars have BultinEntertainmentSystemData .ToList();
因此,我希望获得所有车辆,包括车辆是汽车时内置娱乐系统的信息.我已经看到,如果我直接从DbSet开始,这是可行的,但在这里我正在查看Fleet对象的集合属性.当我在集合属性上使用带有OfType()调用的Include()调用时,我会收到此异常消息:
The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.
解决方法
你不能做你正在尝试的,因为你正在编写的查询被“翻译”为sql. sql中没有“OfType”方法,并且OfType未设置为对象的属性,因此会出现此错误.理想情况下,EF会将此转换为仅表示从包含Type Car的表中获取数据,但事实并非如此.
public class Vehicle { public string Type {get; set;} //you need the setter here for EF } public class Car : Vehicle { public Car() { Type = "Car"; } } DataContext.Fleets .Include(x => x.Vehicles.Select(y => y.EngineData)) // Not specific to Car or Truck .Include(x => x.Vehicles.Where(x => x.Type == "Car").Select(y => y.BultinEntertainmentSystemData)) // Only Cars have BultinEntertainmentSystemData .ToList();
这只是我现在想出来的,你可能需要改进它.使用字符串来定义这样的东西可能并不理想,尝试将其作为枚举等等.