【问题标题】:EF Migrations drops index when adding compsite index添加复合索引时,EF Migrations 删除索引
【发布时间】:2014-09-26 08:22:21
【问题描述】:

我注意到当我使用外键添加复合索引时,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");
        }
}

【问题讨论】:

  • 你能发布你的实体类的新旧版本吗?
  • 当然,但它没有改变。我只是在数据库中添加一个唯一约束。
  • 不应该被删除,但是复合索引中的列顺序错误,我认为
  • 我很困惑。你说实体类没变,还说给它加了复合索引?
  • @DavidG 我添加了模型和映射类供您观看。

标签: sql entity-framework composite-index


【解决方案1】:

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

但是,在我的具体情况下,一种解决方法是在复合索引中首先创建外键。作为第一个作为正常索引。至少如果我正确阅读了this

【讨论】:

    猜你喜欢
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 2017-01-11
    • 2020-12-27
    • 2018-11-08
    相关资源
    最近更新 更多