简体   繁体   English

实体框架:我可以包含子类型的属性吗?

[英]Entity Framework: Can I Include() properties of subtypes?

I have a TPT inheritance set up in my EF project with one supertype and two subtypes. 我在EF项目中设置了一个TPT继承,其中有一个超类型和两个子类型。 I want to get all objects of the supertype and Include() the navigation properties of the subtypes, to this effect (class names changed to protect the befuddled): 我想获得超类型的所有对象和Include()子类型的导航属性,以达到这种效果(更改类名以保护混乱的对象):

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();

So, I want to get all vehicles, including the info on the built-in entertainment system if the vehicle is a car. 因此,我想获取所有车辆,包括如果车辆是汽车,则包括内置娱乐系统上的信息。 I've seen that this is doable if I'm going straight from the DbSet, but here I'm looking at a collection property of a Fleet object. 我已经看到,如果我直接从DbSet开始,这是可行的,但是在这里,我正在研究Fleet对象的collection属性。 When I use an Include() call with an OfType() call on the collection property, I get this Exception message in reply: 当我对集合属性使用Include()调用和OfType()调用时,得到此异常消息作为答复:

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. 使用虚线路径作为参考导航属性,使用“选择”运算符作为集合导航属性。

Is it possible to Include() properties of subtypes within a collection property? 集合属性中是否可以包含子类型的Include()属性?

You can't do what you are trying because the queries you are writing are "translated" to SQL. 您无法执行尝试的操作,因为您正在编写的查询已“转换”为SQL。 There are no "OfType" method in SQL and OfType is not set as a property on your object, so you get this error. SQL中没有“ OfType”方法,并且未将OfType设置为对象的属性,因此会出现此错误。 Ideally EF would translate this to mean only get data from the table that contains the Type Car, but it does not. 理想情况下,EF会将其转换为仅从包含Type Car的表中获取数据,但不会。

If you add a property on the parent that indicates the type, you can use that one to navigate though. 如果在父级上添加一个指示类型的属性,则可以使用该属性进行导航。

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();

This is just something I came up with now, you might have to refine it. 这只是我现在想到的,您可能需要对其进行完善。 Using strings to define something like this might not be ideal, try making it an enum and so on. 使用字符串定义这样的内容可能并不理想,请尝试将其设为枚举,依此类推。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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