Reputation: 632
I've been working through a tutorial on Udemy and seem to have made a mistake somewhere. In one model EF seems to have added an additional property as a foreign key. Here's the model:
public class Movie
{
public int Id { get; set; }
public string Name { get; set; }
public Genre Genre { get; set; }
public byte GenreId { get; set; }
[Display(Name = "Number in Stock")]
public int NumberInStock { get; set; }
[Display(Name = "Release Date")]
public DateTime? ReleasedOn { get; set; }
public DateTime? AddedOn { get; set; }
}
And here's the migration EF generated from that:
public override void Up()
{
CreateTable(
"dbo.Movies",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
GenreId = c.Byte(nullable: false),
Genre_Id = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Genres", t => t.Genre_Id)
.Index(t => t.Genre_Id);
CreateTable(
"dbo.Genres",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
}
You can see it's added the extra Genre_Id
property and set it as the foreign key.
Why has this happened? And how do I fix it? It took my a while to notice so I have several more migrations since this one, do I run down through them all, fix this (somehow), and back up through them again? Is it easier to just manually change it on the database? Or give up and use that field now as the foreign key?
Upvotes: 2
Views: 3501
Reputation: 12304
When entity framework can't automatically figure out a relationship, it adds a field like XXXXX_Id#. In Entity Framework, the foreign key's data type must match the data type of the entity you are relating to, so even though the name follows the convention it is not used. See here for relationship conventions.
Upvotes: 2