Joe Steele
Joe Steele

Reputation: 691

Entity Framework 4.3 to Entity Framework 5 Mapping Exception

I'm in the process of migrating a project from Entity Framework 4.3 running on .net 4 to Entity Framework 5 running on .net 4.5. Without making any changes, when I try to run the project the code-first model configuration fails with a System.Data.MappingException with the message:

(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]

The message does not specify which entity or relationship is causing the problem and my model is reasonably complex. Is there any way that I can get some more helpful information to to make it easier to diagnose the problem?

Upvotes: 4

Views: 1322

Answers (1)

Joe Steele
Joe Steele

Reputation: 691

Ladislav was correct to suggest an inheritance problem. It looks like Entity Framework 4.3 and Entity Framework 5 behave a little differently when it comes to code-first Table Per Hierarchy configurations.

In this case I had four derived types each with their own configuration class derived from EntityTypeConfiguration<T>. The base, abstract type did not have a configuration registered with the model builder. This was not a problem under EF 4.3 which simply created a table named after the base type with a 'Discriminator' column to distinguish between the types.

To get the same behaviour with EF 5 it was necessary to create an empty configuration class

public class MyBaseConfiguration : EntityTypeConfiguration<MyBase> 
{
  // Nothing happening here
}

and then register it with the model builder

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

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

Upvotes: 4

Related Questions