【问题标题】:Why IMutableEntityType.BaseType is null for entities that inherit directly from a base class?为什么 IMutableEntityType.BaseType 对于直接从基类继承的实体为空?
【发布时间】:2019-06-01 14:32:34
【问题描述】:

我定义了以下类:

public class DeletableEntity
{
    public bool IsDeleted { get; set; }
}

public class ClassA : DeletableEntity
{
}

public class ClassB : ClassA
{        
}

在 OnModelCreating 中,我只得到从 DeletableEntity 继承的实体,如下所示:

    foreach (var entityType in builder.Model.GetEntityTypes())
    {
        if (typeof(DeletableEntity).IsAssignableFrom(entityType.ClrType) == true)
        {
            var et = entityType.BaseType;
        }
    }

有趣的是 ClassA 有 entityType.BaseType == null 但 ClrType.BaseType 清楚地表明 ClassA 继承自 DeletableEntity:

:

对于 ClassB,entityType.BaseType 是预期的 ClassA:

为什么第一个继承者的父类被忽略?这是设计的吗?

PS:我使用的是 EF Core 2.2。

【问题讨论】:

    标签: entity-framework asp.net-core-mvc ef-core-2.0


    【解决方案1】:

    因为基础class和基础entity是有区别的。

    IEntityType 表示映射为 EF Core entity 的类。 IEnityType 的类型 BaseType 属性也是 IEnityType。但在您的示例中,DeletableEntity 只是一个基类,而不是基实体,因此该属性返回 null

    可能最好的解释是属性声明:

    //
    // Summary:
    //     Gets the base type of the entity. Returns null if this is not a derived type
    //     in an inheritance hierarchy.
    IEntityType BaseType { get; }
    

    其中“继承层次结构”指的是 EF Inheritance

    EF 模型中的继承用于控制实体类中的继承如何在数据库中表示。

    还有Inheritance (Relational Database)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-14
      • 2011-06-12
      • 1970-01-01
      • 2016-09-02
      • 2023-04-01
      • 1970-01-01
      • 2011-04-30
      相关资源
      最近更新 更多