mishap
mishap

Reputation: 8515

Entity Framework code first FK field

I have two classes:

public class Fighter
{
    public int FighterID { get; set; }
    public int DivsionID { get; set; }
    public string Name { get; set; }
    //...
    public virtual Division Division { get; set; }
}

public class Division
{
    public int DivisionID { get; set; }
    public string Name { get; set; }
    public int? FromWeight { get; set; }
    public int? ToWeight { get; set; }
    public ICollection<Fighter> Fighters { get; set; }
}

Why do I have Division_DivisionID on my Fighters table ? I thought the DevisionID should be the FK. enter image description here

Upvotes: 0

Views: 166

Answers (2)

Anderson Fortaleza
Anderson Fortaleza

Reputation: 2459

You are mixing the EF FK Association concept with your database FK concept, they are not the same. The FK Association concept on EF was introduced so you could do things like lookups and data binding more easily (like DropDownList data binding for example).

The ER FK concept that is created in your table is a mapping for the composition you have on the Fighter class, in this case the Division property. The naming of that table column follows EF's rules.

For more on the EF FK Association read this article.

Upvotes: 2

undefined
undefined

Reputation: 34248

I wrote an article on how this works, take a look at http://blog.staticvoid.co.nz/2012/07/entity-framework-navigation-property.html - See How does Entity Framework detect Navigation Properties

In short this is due to a convention which says FKs are named

<LocalPropertyName>_<ForeignIdPropertyName>

Also see Entity Framework Navigation Property generation rules

to make EF name the FK DivisionID, add the following to your modelbuilder

        modelBuilder.Entity<Fighter>()
            .HasRequired(f => f.Division)
            .WithMany(d => d.Fighters)
            .HasForeignKey(f => f.DivisionID);

Upvotes: 2

Related Questions