Snæbjørn
Snæbjørn

Reputation: 10792

Add-Migration won't detect changes to foreign key

EF Migrations can't seem to detect my changes to the model, as it just generates an empty Up() / Down() when running Add-Migration.

The database is not out of sync with my migrations.

Migration file: Migration file

__migrationhistory table: __migrationhistory table

Before

public class House {
    public virtual ICollection<Person> UsedBy { get; set; }
}

public class Car {
    // ...
}

public class Person {
    public int? UsingId { get; set; }
    public virtual House Using { get; set; }
}

Mapping

this.HasOptional(t => t.Using)
                .WithMany(t => t.UsedBy)
                .HasForeignKey(t => t.UsingId);

After

public class House {
    // removed
}

public class Car {
    // added
    public virtual ICollection<Person> UsedBy { get; set; }
}

public class Person {
    public int? UsingId { get; set; }
    // changed type
    public virtual Car Using { get; set; }
}

Mapping

this.HasOptional(t => t.Using)
                .WithMany(t => t.UsedBy)
                .HasForeignKey(t => t.UsingId);

Upvotes: 2

Views: 752

Answers (1)

Christoph Fink
Christoph Fink

Reputation: 23113

As already said in my comment I could reproduce this, but renaming the Using property also helped.
If that is not an option you could use the following code added manually to the migration:

public override void Up()
{
    DropForeignKey("dbo.People", "UsingId", "dbo.Houses");
    AddForeignKey("dbo.People", "UsingId", "dbo.Cars", "Id");
}

public override void Down()
{
    DropForeignKey("dbo.People", "UsingId", "dbo.Cars");
    AddForeignKey("dbo.People", "UsingId", "dbo.Houses", "Id");
}

This is based on what Add-Migration creates when renaming the property.

Upvotes: 2

Related Questions