EF核心使用表拆分生成错误的外键

时间:2019-06-26 11:19:35

标签: c# entity-framework entity-framework-core

我有两个进行表拆分的实体-Order和OrderDetail(Order的一部分),CompositeOrder和CompositeOrderDetail(CompositeOrder的一部分)。另外,OrderDetail应该包含到CompositeOrderDetail的链接,而CompositeOrder应该包含Order实体的集合。我尝试配置这些关系,但是实体框架在OrderDetail中使用CompositeOrderId1代替CompositeOrderId作为外键。我应该如何配置实体来解决该问题?

public class OrderDetail
{
    public Guid Id { get; set; }

    public CompositeOrderDetail CompositeOrder { get; set; }
}

public class Order : OrderDetail
{
    ...
}

public class CompositeOrder
{
    public Guid Id { get; set; }

    public CompositeOrderDetail Detail { get; set; }

    public ICollection<Order> Orders { get; set; }
}

public class CompositeOrderDetail
{
    public Guid Id { get; set; }
}


   public void Configure(EntityTypeBuilder<CompositeOrder> builder)
    {
        builder.ToTable("CompositeOrder");
        builder.HasMany(co => co.Orders)
            .WithOne()
            .HasForeignKey("CompositeOrderId")
            .IsRequired();
        builder.HasOne(m => m.Detail)
            .WithOne()
            .HasForeignKey<CompositeOrderDetail>(m => m.Id);
    }

    public void Configure(EntityTypeBuilder<OrderDetail> builder)
    {
        builder.ToTable("Order")
            .HasOne<Order>()
            .WithOne()
            .HasForeignKey<OrderDetail>(o => o.Id);
       builder.HasOne(o => o.CompositeOrder)
            .WithMany()
            .HasForeignKey("CompositeOrderId");
    }

    public void Configure(EntityTypeBuilder<Order> builder)
    {
        builder.ToTable("Order")
            .HasBaseType((string)null);
    }

0 个答案:

没有答案