Question

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.

Était-ce utile?

La 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).

Autres conseils

I suspect that the Entity Framework adds an index to foreign keys - even when the foreign key is already indexed because it is also the primary key. Maybe it's an oversight or maybe it's a low priority for the framework developers. Either way, you can adjust the Up() method yourself. See item 7 on this useful blog Tips for Entity Framework Migrations

Try making both tables inherit from an abstract class as described here

public abstract class ProductBase
{
  [Key]
  public int ProductId { get; set; }
}

public class Product: ProductBase
{
  public int Value { get; set; }
}

public class Service : ProductBase
{
    public int OtherValue { get; set; }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top