实体和派生实体的EF Core TPC映射

问题描述 投票:0回答:0

我有定义为 TPC 的 EF Core 实体。

实体:

public class Customer
{
  public long Id { get; set; }
  public ICollection<ProformaInvoice> ProformaInvoices { get; set; }
  public ICollection<Invoice> Invoices { get; set; }
}

public class Invoice
{
  public long Id { get; set; }
  public double Value { get; set; }
  public Customer Customer { get; set; }
}

public class ProformaInvoice : Invoice       // configured as TPC
{
  public string Notes { get; set; }
}

上下文:

public class MyContext : DbContext
{

  protected override void OnModelCreating(ModelBuilder builder)
  {
    base.OnModelCreating(builder);

    var customerBuilder = builder.Entity<Customer>();
    customerBuilder.HasKey(x => x.Id);
    customerBuilder.HasMany(x => x.ProformaInvoices).WithOne(x => x.Customer).OnDelete(DeleteBehavior.Cascade);
    customerBuilder.HasMany(x => x.Invoices).WithOne(x => x.Customer).OnDelete(DeleteBehavior.Cascade);

    var invoiceBuilder = builder.Entity<Invoice>();
    invoiceBuilder.UseTpcMappingStrategy();             // TPC
    invoiceBuilder.HasKey(x => x.Id);
    invoiceBuilder.Property(x => x.Value).IsRequired();

    var proformaInvoiceBuilder = builder.Entity<ProformaInvoice>();
    //proformaInvoiceBuilder.HasKey(x => x.Id);         // do not configure key else get error "A key cannot be configured on 'ProformaInvoice' because it is a derived type. The key must be configured on the root type 'Invoice'."
    proformaInvoiceBuilder.Property(x => x.Value).IsRequired();
    proformaInvoiceBuilder.Property(x => x.Notes).IsRequired();
  }

  public DbSet<Customer> Customers => Set<Customer>();
  public DbSet<ProformaInvoice> ProformaInvoices => Set<ProformaInvoice>();
  public DbSet<Invoice> Invoices => Set<Invoice>();

}

创建迁移:

$ dotnet ef migrations add AddEntities

错误:

无法在“Customer.Invoices”和“Invoice.Customer”之间创建关系,因为“Customer.ProformaInvoices”和“ProformaInvoice.Customer”之间已经存在关系。导航只能参与单一关系。如果要覆盖现有关系,请先在“OnModelCreating”中的导航“Invoice.Customer”上调用“忽略”。

我该如何解决这个问题?我怀疑这与 TPC 设计有关。

(注意我无法更改为 TPH/TPT,我需要使用 TPC...这只是一个简化的最小复制。)

c# entity-framework-core ef-core-7.0
© www.soinside.com 2019 - 2024. All rights reserved.