简体   繁体   中英

How to map multiple nested class to one table in Entity Framework Core 6.0

I am building an API in.Net core using EF core 6.0 as ORM. I have class structure as given below. Can you please guide me on how can I map fields of all 3 classes to one sql table. With the code given, I was not able to map beyond the fields of first class.

B2BOrder.cs

    public string CustomerCode { get; set; }
    public string DocumentIdentifier{ get; set; }

    public OrderHeader OrderHeader { get; set; }

OrderHeader.cs

    public string OrderType { get; set; }

    public string ContractNumber { get; set; }

    public string Activity { get; set; }

    public OrderDetails OrderDetails { get; set; }

OrderDetails.cs

    public string OrderStatusCode { get; set; }

    public string CustomerOrderReference { get; set; }

    public string PurchaseOrderNumber { get; set; }

DB Context Class

public class LucRepository : DbContext
{
    public virtual DbSet<B2BOrder> B2BOrders { get; protected set; }
    public LucRepository(DbContextOptions options) : base(options)
    {

    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("Luc");
        modelBuilder.ApplyConfiguration(new B2BOrderMapping());       

    }
}

B2BOrderMapping.cs

 public class B2BOrderMapping : IEntityTypeConfiguration<B2BOrder>
    {
        public void Configure(EntityTypeBuilder<B2BOrder> builder)
        {
            builder.ToTable("B2BOrders");
            builder.HasKey(x => x.Id);

            builder.Property(x => x.Id).HasColumnName("Id").ValueGeneratedOnAdd();
            builder.Property(x => x.DocumentIdentifier).HasColumnName("DocumentIdentifier");
            builder.Property(x => x.CustomerCode).HasColumnName("CustomerCode");

        }
    }

Thanks in advance !

You can use, Owned Entities like @Steve-py mentioned or you can use Inheritance like below:

B2BOrder.cs

public class B2BOrder : OrderHeader
{
    public string CustomerCode { get; set; }

    public string DocumentIdentifier{ get; set; }
}

OrderHeader.cs

public class OrderHeader : OrderDetails
{
    public string OrderType { get; set; }

    public string ContractNumber { get; set; }

    public string Activity { get; set; }
}

OrderDetails.cs

public class OrderDetails
{
    public string OrderStatusCode { get; set; }

    public string CustomerOrderReference { get; set; }

    public string PurchaseOrderNumber { get; set; }
}

and in db context only add B2BOrder as virtual dbSet.

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