jaffa
jaffa

Reputation: 27350

Codefirst foreign key name has repeated table name - how to set explicitly?

I have 2 tables: 1) Parent 2) Child

In codefirst I have the following definition:

public class Parent 
{
    public int ParentId { get; set; }
    public ICollection<Child> child { get; set; }
}

However in the db, the child table has the following foreign key defined:

ParentParentId (FK, int, NULL)

How do I ensure it just specifies ParentId in the foreign key? Do I need to explicitly set the parent key using the fluent configuration?

Upvotes: 0

Views: 272

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

Yes you must either include Foreign key property in the child entity:

public class Child
{
    public int ChildId { get; set; }
    public int ParentId { get; set; } // FK
    public virtual Parent { get; set; }
}

Or you must rename the column with fluent API:

modelBuilder.Entity<Child>()
            .HasRequired(c => c.Parent)
            .WithMany(p => p.Childs)
            .Map(m => m.MapKey("ParentId"));

Upvotes: 1

Related Questions