2

将实体子类化并将子类实例添加到 Context 的 DbSet 集合会导致以下错误Mapping and metadata information could not be found for EntityType 'Namespace_Name.SubClass_Entity_Name'

细节:

上下文类有一个属性 DbSet。
我们在不同的程序集中有几个实体,

  1. BaseClass(属于 Assembly1 的 BaseClass)
  2. DerivedClass : BaseClass (DerivedClass 属于 Assembly2)

在运行时,当我们将派生类的实例添加到 Context 时,我们会得到上述异常。

注意:当 DerivedClass 与 BaseClass 属于同一程序集时,不会发生此异常。

问题:
为什么我们有这个问题,只是因为子类属于一个单独的程序集?
为什么我们不为属于同一程序集的子类面对这个问题?


更新:

我找到了一个修复方法,就是重写 OnModelCreating 方法并注册 DerivedClass,如下所示modelBuilder.Entity< DerivedClass>();

4

1 回答 1

0

另一种解决方法:如果您使用 TPT 映射,您也必须注册您的派生类,但这样更有意义。

Map(m => 
{
  m.ToTable("BaseClassTableName")
}.Map<DerivedClass>(m =>
{
  m.ToTable("DerivedClassTableName")
}
于 2021-11-16T10:26:38.493 回答