Prevent extra foreign key columns in One to Many relationship

c# ef-code-first entity-framework entity-framework-6 one-to-many

Question

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?

1
3
4/3/2015 8:31:37 PM

Accepted Answer

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.

2
4/3/2015 10:22:29 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow