EF 中的多态多对多关系

Plymorphic Many to Many relationships in EF

我在一个实体类型上有一个多态集合,其中包含一个对象集合,这些对象是它的子类型。 子类型都存储在数据库中的不同表中。

我需要在流利的 API 中映射这种关系,以便我可以管理级联。 这是我拥有的实体结构示例 ...

[Table("Reports", "Reporting")]
class Report
{
    [Key]
    public int Id { get; set; } 
    public virtual ICollection<Entry> Entries { get; set; }
}

abstract class Entry
{
   [Key]
   public int Id {  get; set; }
   public virtual ICollection<Report> Reports { get; set; }
}

[Table("InvoiceEntries", "Reporting")]
class InvoiceEntry : Entry
{
    public ICollection<Invoice> Invoices { get; set; }
}

... <other types> like InvoiceEntry each mapped to their own tables ...

在我的模型配置中我有...

builder.Ignore<Entry>();

更新

如评论中所述,这里有一个关于多态关系的很好的答案...

https://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-3-table-per-concrete-type-tpc-and-choosing-strategy-guidelines

...我的场景是 "Table Per Concrete Type" 多对多 关系作为多态关系。

虽然描述很好,但似乎没有涵盖这种情况

嗯……好吧,这很奇怪…… 所以事实证明,这实际上只有在您足够好地让它知道您从子基类型派生的类型无法以这种方式工作时才有效。

例子...

[Table("Reports", "Reporting")]
class Report
{
    [Key]
    public int Id { get; set; } 
    public virtual ICollection<Entry> Entries { get; set; }
}

abstract class Entry
{
   [Key]
   public int Id {  get; set; }
   public virtual ICollection<Report> Reports { get; set; }
}

[Table("InvoiceEntries", "Reporting")]
class InvoiceEntry : Entry
{
    public ICollection<Invoice> Invoices { get; set; }
}

class PaymentEntry
{
   [ForeignKey("Payment")]
   public int PaymentId { get;set; }

   public virtual Payment Payment { get; set; }
}

事实证明,问题在于报告对象需要使用流畅 API 映射 PaymentEntry 子类型,并且关闭级联以防止多个级联路径。

如果所有子类型都只有InvoiceEntry样式,多对多映射EF可以自己搞定。

为避免这种情况,要么流畅地编写其他关系脚本以避免级联问题,要么使所有子类型成为多对多关系。