0

I have a series of models that relate to a parent model, and the series of models have a child table that relates back to the original parent, so:

Public Class A
{
    [Key]
    public long AId {get; set;}
    public string Name {get; set;}
}

Public Class B1
{
    [Key]
    public long Id {get; set;}
    [ForeignKey("AId")]
    public virtual A a {get;set;}
    public virtual ICollection<C> Cs {get;set}
}

Public Class B2
{
    [Key]
    public long AId {get; set;}
    [ForeignKey("AId")]
    public virtual A a {get;set;}
    public virtual ICollection<C> Cs {get;set}
}

Public Class C
{
    public long CId {get; set;}
    public long AId {get; set;}
    [ForeignKey("AId")]
    public virtual A a {get;set;}
}

The ApplicationDBContext ties the one to one/zero entities together with fluent api, but I can't figure out how to tie c. The context looks like this:

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }

    public DbSet<A> As { get; set; }
    public DbSet<B1> B1s { get; set; }
    public DbSet<B2> B2s { get; set; }
    public DbSet<C> Cs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<B1>().HasOne(x => x.a).WithOne().HasForeignKey<A>(p => p.Id);
    }

I want to tie C in with something like this:

modelBuilder.Entity<B1>().HasMany(x => x.Cs).WithOne(y => y.a); 

But it doesn't like this because it is referencing table A, the parent, which is what I want it to do. This is my first attempt at using Core and I am not finding a way to tie 3 tables together with fluent api. I was able to do this in EF 4.6, so I am assuming this should be possible in Core.

Any help would be appreciated.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
CHADev
  • 5
  • 1
  • 5
  • does this previous answer also address your question? https://stackoverflow.com/a/35507286/1260204 – Igor Oct 10 '19 at 15:35

1 Answers1

0

I figured it out....

modelBuilder.Entity<B1>().HasMany(x => x.Cs).WithOne().HasForeignKey(y => y.AId); 

Hopefully this helps someone else out.

CHADev
  • 5
  • 1
  • 5