简体   繁体   中英

One to one or zero mapping in Entity Framework Core 2.2

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.

I figured it out....

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

Hopefully this helps someone else out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM