Why am I getting an extra foreign key column with Entity Framework Code First Foreign Key Attributes?

前端 未结 2 1991
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 20:25

I recently came across this strange problem with Entity Framework Code First.

My class looks like this

public class Status
{
        [Key]
        pu         


        
2条回答
  •  既然无缘
    2020-12-13 21:06

    Your Member_MemberID column is created because of the Member.Statuses property. I can imagine that this is not what you want. Probably members and statuses should exist independent of each other, so you need a junction table.

    I don't know if you already use the OnModelCreating override of the DbContext, but that's the place to change the mapping between Member and Status:

    protected override void OnModelCreating(DbModelBuilder mb)
    {
        mb.Entity().HasMany(m => m.Statuses).WithMany();
    }
    

    This will create a table MemberStatuses table with the two Id columns as foreign keys. This is a way to model a many-to-many relationship without a navigation property on the "other" side of the association. (I don't think you want a Members property in Status).

提交回复
热议问题