Entity Framework 代码优先 "join table"

Entity Framework Code First "join table"

我正在使用 Entity Framework Code First。

我有一个名为 Notes 的实体

我还有其他实体,例如 商业合作伙伴 机会 工单

所有这些实体都可能有注释。

最好的建模方法是什么

1.) 在备注 table 中有指向业务合作伙伴、机会和工作订单的可选外键。然后只需设置与注释相关的可选键

2.) 有中间 tables 例如 BusinessPartnerNotes,有两个字段 BusinessPartnerId 和 NoteId

需要注意的是,一条笔记永远不会同时与两个实体相关。

如有任何帮助或建议,我们将不胜感激。

根据您对基数的描述,并假设 Notes for BusinessPartners 与 Notes for Opportunities 具有相同的格式,我会采用最简单的方法(您列表中的选项 1)。

class Note
{
    public int Id { get; set; }
    public string Content { get; set; }
}
class BusinessPartner
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Note> Notes { get; set; }
}
class Opportunity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Note> Notes { get; set; }
}

应该生成下表:

Notes
  Id
  Content
  BusinessPartner_Id
  Opportunity_Id
BusinessPartners
  Id
  Name
Opportunities
  Id
  Name