0

I wondered if anyone can advise me on how to resolve a problem with regards to using FluentAPI to map a couple of tables.

I have Parent table that has our key called ID Then a Child table with two fields idA & idB.

The primary key in the parent table links to either idA or idB, not both.

public Parent()
    {
        this.ChildA = new HashSet<Child>();
        this.ChildA = new HashSet<Child>();
    }
    public virtual ICollection<Child> ChildA { get; set; }
    public virtual ICollection<Child> ChildB{ get; set; }
}

public Child()
    public virtual Parent parent { get; set; }
}

There is much I can do about the relationship/table design because it is legacy and cannot be changed. Just need to understand the correct FluentAPI to use to account for this issue. Above example it what I envisaged would be needed along with something like...

modelBuilder.Entity<Child>().HasRequired<Parent>(p => p.parent).WithMany(q => q.childs).HasForeignKey(r =>  r.idA);
modelBuilder.Entity<Child>().HasRequired<Parent>(p => p.parent).WithMany(q => q.childs).HasForeignKey(r =>  r.idB);

1 Answers1

0

I believe I was able to get the correct mapping you are looking for. I added naviation properties to the POCO which allows Entity Framework to know how to use the foreign keys in code.

public class Child
{
    public int Id { get; set; }
    public virtual Parent ParentA { get; set; }
    public virtual Parent ParentB { get; set; }

    public Child() { }
}

To map these navigation properties to you already existing foreign key columns, I used the FluentAPI Map method.

modelBuilder.Entity<Child>().HasRequired<Parent>(p => p.ParentA).WithMany(q => q.ChildA).Map(m => m.MapKey("idA")).WillCascadeOnDelete(false);
modelBuilder.Entity<Child>().HasRequired<Parent>(p => p.ParentB).WithMany(q => q.ChildB).Map(m => m.MapKey("idB")).WillCascadeOnDelete(false);

With this, I have indicated ParentA populates the ChildAcollection, and ParentB populates the ChildB collection. The Map method is what allows me to map to your already existing FKs, and I don't have to include them with the POCO as a property.

Note that each POCO that maps to a table must have a primary key. Does your already existing child table have a PK? If not, you may have some further trouble. I recommend reading this SO post about it. Entity Framework: table without primary key

Community
  • 1
  • 1
Jason Tyler
  • 1,331
  • 13
  • 26
  • The child table has no PK at all. Just this silly referencing headache. Thank you I will give this a good go, really appreciate your assistance. –  Feb 23 '17 at 07:17