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 attempting to figure out how to set up EF to manage the following circumstance involving one parent and several kids:

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;}
}

My parent class's created table appears to be perfect. However, Parent ParentId and Parent ParentId1 have been created as new columns to my kid table, and ParentId does not have a foreign key defined.

How can I make sure that ParentId is the only foreign key in the Child table and forbid the addition of any more?

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

Accepted Answer

You could follow these steps to fix the problem:

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

In this approach, the connection between the collection of youngsters involved and theParentId FK Real Estate (This connection is what's causing theParent_ParentId1 Column FK).

You may currently believe that you have one one-to-many relationship and two one-to-one relationships, but in reality, you actually have three one-to-many ties (the first two have unidirectional navigation). This is how it would look if you configured those relationships using the Fluent Api:

  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);

However, this model ought to be true for the reasoning that you are probably seeking for.

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