entity-frameworkef-code-firstentity-framework-migrationstable-per-type

Prevent Entity Framework from adding duplicated keys in migration with table per type inheritance


I have a simple model using table per type inheritance for some entities. The problem is that when I generate the migration using Add-Migration, It creates a duplicated index on the child class' primary key.

Class definitions:

class Product
{
    [Key]
    public int ProductId { get; set; }
    public int Value { get; set; }
}
class Service : Product
{
    public int OtherValue { get; set; }
}

And in my context, I specify the table names for both classes

class ProductContext : DbContext
{
    virtual public DbSet<Product> ProductSet { get; set; }
    virtual public DbSet<Service> ServiceSet { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Product>().ToTable("Product");
        modelBuilder.Entity<Service>().ToTable("Service");
    }
}

Running Add-Migration results in the following:

public override void Up()
{
    CreateTable(
        "dbo.Product",
        c => new
            {
                ProductId = c.Int(nullable: false, identity: true),
                Value = c.Int(nullable: false),
            })
        .PrimaryKey(t => t.ProductId);

    CreateTable(
        "dbo.Service",
        c => new
            {
                ProductId = c.Int(nullable: false),
                OtherValue = c.Int(nullable: false),
            })
        .PrimaryKey(t => t.ProductId)
        .ForeignKey("dbo.Product", t => t.ProductId)
        .Index(t => t.ProductId);

}

It creates an additional index on Service.ProductId when it's already the primary key. Is there some annotation I am missing in order to prevent the index from being added?

Tested with both EF5 and EF6 with the same results.


Solution

  • Just for whom (still) facing this problem, as I understand it's a bug fixed in version 6.1.1 of EF (https://entityframework.codeplex.com/workitem/1035).

    So just updating to the latest version of EF should fix it. But if you couldn't or wouldn't update, the workaround is just as simple as deleting duplicate Index in generated migration file and save (don't also forget to disable AutomaticMigrationsEnabled if enabled).