添加复合索引时,EF迁移会删除索引

时间:2014-09-26 08:22:21

标签: sql entity-framework composite-index

我注意到当我使用外键添加复合索引时,EF删除了外键上的索引。所以我需要更好地理解复合索引:)

我使用this answer添加了复合索引,并生成了我的EF代码第一个迁移文件。

添加综合指数:

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

迁移文件:

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...
}

我不明白为什么它需要删除我的外键索引。据我所知,属性可以在多个索引中使用而不会出现问题。那为什么会掉线?这会不会使连接速度变慢?

型号:

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; }
}

映射:

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 个答案:

答案 0 :(得分:1)

我得出结论,这是EF中的错误。

但是在我的特定情况下,解决方法是在复合索引中首先使外键。由于第一个充当正常指数。至少如果我正确阅读this

相关问题