Brian Vallelunga
Brian Vallelunga

Reputation: 10201

Prevent extra foreign key columns in One to Many relationship

I'm trying to figure out how to configure EF to handle the below situation involving one parent and multiple children:

public class Parent
{
    public int ParentId {get; set;}

    [ForeignKey("SpecialChildOneId")]
    public virtual Child SpecialChildOne {get; set;}
    public int? SpecialChildOneId {get; set;}

    [ForeignKey("SpecialChildTwoId")]
    public virtual Child SpecialChildTwo {get; set;}
    public int? SpecialChildTwoId {get; set;}

    public virtual ICollection<Child> Children {get; set;}
}

public class Child
{
    public int ChildId {get; set;}
    public int ParentId {get; set;}
}

The generated table for my parent class looks fine. On my child table though I get two extra columns added, Parent_ParentId and Parent_ParentId1, and no foreign key is set on ParentId.

How can I enforce ParentId to be the only foreign key on the Child table and prevent additional foreign keys from being added?

Upvotes: 3

Views: 1580

Answers (1)

ocuenca
ocuenca

Reputation: 39346

To resolve this issue you could do this:

public class Child
{
   public int ChildId {get; set;}
   [ForeignKey("Parent")]
   public int ParentId {get; set;}
   public virtual Parent Parent{get;set;}
}

This way, the relationship where is involved the collection of children is asociated with the ParentId FK property (This is the relationship that is creating the Parent_ParentId1 FK Column).

Now,you are probably thinking that you have two one-to-one relationships and one one-to-many, but that's not true, you really have three one-to-many relationships (the first two have unidirectional navigation). If you configure those relationships using Fluent Api, It would be like this:

  modelBuilder.Entity<Parent>()
              .HasOptional(p=> p.SpecialChildOne )
              .WithMany()
              .HasForeignKey(p=> p.SpecialChildOneId );

  modelBuilder.Entity<Parent>()
              .HasOptional(p=> p.SpecialChildTwo )
              .WithMany()
              .HasForeignKey(p=> p.SpecialChildTwoId );

  modelBuilder.Entity<Child>()
              .HasRequired(c=> c.Parent)
              .WithMany(p=>p.Children)
              .HasForeignKey(p=> p.ParentId);

But for the logic that probably you are looking for, this model should work.

Upvotes: 2

Related Questions