简体   繁体   English

使用 Entity Framework Core 在抽象基类中映射导航属性

[英]Mapping navigation property in abstract base class with Entity Framework Core

I have different Cars and each has a specific car type.我有不同的汽车,每个都有特定的汽车类型。 All cars inherit from same abstract base class CarBase.所有汽车都继承自同一个抽象基类 CarBase。 The CarBase class has a navigaiton property to CarType. CarBase 类具有 CarType 的导航属性。

public abstract CarTypeBase 
{ 
    public string Name { get; set; }
}

public class FordCarType : CarTypeBase 
{

}

public abstract class CarBase {
     public CarTypeBase CarType { get; set; }

     public string GetName() {
           return CarType.Name;
     }      
}

public class Ford : CarBase {

}

The Ford is mapped with the following EF mapping configuration: Ford 使用以下 EF 映射配置进行映射:

builder.HasOne(o => (FordCarType) o.CarType);

For the CarTypeBase class I'm using the default Table per Hierarchy (TPH) mapping of Entity Framework, so the CarTypeBase table has a discriminator column.对于 CarTypeBase 类,我使用实体框架的默认 Table per Hierarchy (TPH) 映射,因此 CarTypeBase 表有一个鉴别器列。 And the Ford table has a Foreign Key to CarTypeBase table.福特表有一个 CarTypeBase 表的外键。

The problem is that the Ford CarType navigation property is always null if I'm trying to access it for instance in the GetName() method.问题是福特 CarType 导航属性始终为空,如果我尝试在 GetName() 方法中访问它。 If I use instead the concrete type FordCarType the CarType property will be mapped in the Ford class.如果我使用具体类型 FordCarType,则 CarType 属性将映射到 Ford 类中。

So maybe what I want to achieve is not possible with EF or isn't possible at all?那么也许我想要实现的目标在 EF 中是不可能的,或者根本不可能实现?

Late to the party but, shouldn't this be:聚会迟到了,但是,这不应该是:

public abstract CarTypeBase 
{ 
    public string Name { get; set; }
}

public abstract class CarBase : CarTypeBase  {
        
     public string GetName() {
           return this.Name;
     }      
}

public class Ford : CarBase {

}

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

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