EF Migrations drops index when adding compsite index

偶尔善良 提交于 2021-02-19 07:01:50

问题


I noticed EF removed an index on a foreign key when I added a composite index with the foreign key. So I need to understand composite indexes better :)

I added the composite index using this answer and generated my EF code first migration file.

Adding composite index:

this.Property(x => x.Name)
    .HasUniqueIndexAnnotation("IX_UniqueNamePerKey", 0);
this.Property(x => x.TeacherId)
    .HasUniqueIndexAnnotation("IX_UniqueNamePerKey", 1);

Migration file:

public partial class CompositeIndex : DbMigration
{
    public override void Up()
    {
        DropIndex("dbo.Course", new[] { "TeacherId" });
        CreateIndex("dbo.Course", new[] { "Name", "TeacherId" }, unique: true, name: "IX_UniqueNamePerKey");
    }

    // omitted...
}

What I don't understand is why it needs to drop the index on my foreign key. To my knowledge a property can be used in multiple indexes without problems. So why is it dropped? Wouldn't that make joins slower?

Model:

public class Course
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int TeacherId { get; set; }
    public virtual Teacher { get; set; }
}

public class Teacher
{
    public int Id { get; set; }
    public ICollection<Course> Courses { get; set; }
}

Mapping:

public class CourseMap : EntityTypeConfiguration<Course>
{
    protected CourseMap()
        {
            // Primary key
            this.HasKey(t => t.Id);

            // Properties
            this.Property(x => x.Name)
                .IsRequired()
                // below code was added
                .HasUniqueIndexAnnotation("IX_UniqueNamePerKey", 0);
            this.Property(x => x.ForeignKeyId)
                .HasUniqueIndexAnnotation("IX_UniqueNamePerKey", 1);

            // Table & Column Mappings
            this.ToTable("Course");
        }
}

回答1:


I've come to the conclusion that it's bug in EF.

However in my specific case a workaround is to make the foreign key first in the composite index. As the first acts as a normal index. At least if I read this correctly.



来源:https://stackoverflow.com/questions/26055140/ef-migrations-drops-index-when-adding-compsite-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!