Entity Framework 4.3 到 Entity Framework 5 的映射异常

4
我正在将一个基于Entity Framework 4.3和.NET 4的项目迁移到Entity Framework 5和.NET 4.5。在不进行任何更改的情况下,当我尝试运行项目时,代码优先模型配置会因出现 System.Data.MappingException 错误而失败,错误信息如下所示:

(495,10) : error 3034: Problem in mapping fragments starting at lines 495, 536:Two entities with different keys are mapped to the same row. Ensure these two mapping fragments do not map two groups of entities with different keys to the same group of rows.

[5 other similar paragraphs removed]

该错误信息并未指明导致问题的实体或关系,而我的模型相对复杂。有没有什么方法可以获取更详细的信息以便更容易诊断问题?

你正在使用继承吗?这可能会限制你的搜索。 - Ladislav Mrnka
是的,我是的。通过一点搜索可以看到其他人在使用TPH配置时遇到了3034错误,所以这似乎是一个不错的起点,谢谢。 - Joe Steele
1个回答

4
Ladislav正确地指出了继承问题。在使用Code-First Table Per Hierarchy配置时,Entity Framework 4.3和Entity Framework 5的行为略有不同。
在这种情况下,我有四个派生类型,每个类型都有自己的配置类,这些配置类均派生自EntityTypeConfiguration<T>。基本的抽象类型没有在模型构建器中注册配置。这在EF 4.3下不是问题,它只是创建了一个以基本类型命名的表,并添加了一个“Discriminator”列来区分不同的类型。
要在EF 5下获得相同的行为,需要创建一个空的配置类。
public class MyBaseConfiguration : EntityTypeConfiguration<MyBase> 
{
  // Nothing happening here
}

然后将其在模型构建器中注册。

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new MyBaseConfiguration());

        // Add configurations for derived and other types as normal
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接