0

I currently have a EF Context. In my database schema I have the following scenario.

Two Tables, TableA and TableB

Tables are defined as follows:

TableA ( A_ID, name, description)
TableB ( B_ID, C_ID, name, description)

The relationship between TableA and TableB is such that B_ID and C_ID are both FK's to A_ID.

How do I achieve this behaviour in EF by setting up either my ModelBinder (Fluent API) or by annotations. Thanks in advance.

nav
  • 509
  • 4
  • 19

1 Answers1

2

I have solution, but only if You little modify Your entitites by added TableA virtual prop in TableB entity. Example:

public class TableB
{
...
public virtual TableA B { get; set; }
public virtual TableA C { get; set; }
...
}

Then override "OnModelCreating" in context (you may use "HasOptional" instead "HasRequired"):

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<TableB>()
                .HasRequired(x => x.B)
                .WithMany()
                .HasForeignKey(x => x.B_ID).WillCascadeOnDelete(false);

            modelBuilder.Entity<TableB>()
                .HasRequired(x => x.C)
                .WithMany()
                .HasForeignKey(x => x.C_ID).WillCascadeOnDelete(false);

            base.OnModelCreating(modelBuilder);
        }

And one more thing. I do not know how well using my solution for Your "B_ID" primary key. In my project I have a different PK "Id".

Leon Pro
  • 102
  • 9