首页 > 解决方案 > 为什么 IMutableEntityType.BaseType 对于直接从基类继承的实体为空?

问题描述

我定义了以下类:

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-frameworkasp.net-core-mvcef-core-2.0

解决方案


这是因为基类和基实体之间存在差异。

IEntityType表示映射为 EF Core实体的类。的 typeBaseType属性IEnityType也是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 模型中的继承用于控制实体类中的继承如何在数据库中表示。

还有继承(关系数据库)


推荐阅读