简体   繁体   中英

Entity Framework 6 trying to drop non existent Index when renaming

As a newcomer to EF migrations, I was surprised by the following behaviour, and wondered if it's intentional (ie there's a switch to make it go away).

When I rename a column, I have the following relevant lines inside an EntityTypeConfiguration class:

Property(x => x.MyColumn).HasColumnName(@"MyColumn").HasColumnType("nvarchar").IsOptional();

And, crucially:

HasOptional(a => a.RelatedTable).WithMany(b => b.ThisTable).HasForeignKey(c => c.MyColumn).WillCascadeOnDelete(false);

Which is, as I understand it, establishing a foreign key relationship. When I rename MyColumn to MyColumn2, the migration that is created looks like this:

public override void Up()
{
    RenameColumn(table: "dbo.ThisTable", name: "MyColumn", newName: "MyColumn2");
    RenameIndex(table: "dbo.ThisTable", name: "IX_MyColumn", newName: "IX_MyColumn2");
}

However, MyColumn is not indexed on ThisTable . I realise that creating indexes for a foreign key relationship is advisable; is this why EF assumes there is one?

Note that the EF model was generated from the DB initially using the EF Reverse POCO Generator.

It's intentional. Code First migrations are based purely on model (data annotations, fluent configuration) and assume the previous database state is created using migration as well. Since EF default convention is to create index for FK columns, the migration assumes that the index exists and tries to rename it.

You can solve it in two ways. Either edit the generated migration and remove the RenameIndex (and other index related commands), or turn off (remove) the default FK index convention:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<ForeignKeyIndexConvention>();
    // ...
}

Please note that the later will affect your future model modifications and you have to explicitly opt for index on FK columns (which cannot be done if the entity does not have explicit FK property). Also if you rename some of the exiting FK columns which do have an index, you'll have to add RenameIndex (or DropIndex / CreateIndex`) commands manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM