EF Core Fluent API 与两个相同类型实体的映射关系

Mapping Relationships with EF Core Fluent API with two entities of the same type

我一直在尝试使用流畅的 api 为下图配置适当的映射。 (如果有人将其标记为重复,看在上帝的份上,请包括相关内容 link!我花了好几天时间梳理 Whosebug。)

我的主要目标是所有实体都将有一个 EnterpriseID 用作分片键。

企业 table 包含两个联系人,一个是 PrimaryContact 一个是 BillingContact。

我想做的是使用生成的代码 GUID ID 以及两个联系人(主要和计费)创建一个新企业,分配 Enterprise ID 并在 TrackingState 上调用 SaveChanges。添加了对象层次结构(此时为 Enterprise->Contacts- >地址。

没有任何 Fluent 映射,EF Core 2.1 说.. "Both relationships between 'Contact' and 'Enterprise.BillingContact' and between 'Contact' and 'Enterprise.PrimaryContact' could use {'EnterpriseID'} as the foreign key. To resolve this configure the foreign key properties explicitly on at least one of the relationships."

我尝试了很多配置,要么最终得到的数据库只定义了企业 table 中的一个 Contact 属性,要么整个混乱变成了 FK/循环地狱。

这是当前 class 个存根..

public class Enterprise
{
  public Guid ID {get; set;}
  public Contact PrimaryContact {get; set;}
  public Contact BillingContact {get; set;}
}

public class Contact
{
  public Guid ID {get; set;}
  public Guid EnterpriseID {get; set;}
  public string FName {get; set;}
  public string LName {get; set;}
  public Address Address {get; set;}
}

public class Store
{
  public Guid ID {get; set;}
  public Guid EnterpriseID {get; set;}
  public Contact PrimaryContact {get; set;}
}

public class Order
{
  public Guid ID {get; set;}
  public Guid EnterpriseID {get; set;}
  public Guid StoreID {get; set;}
  public Contact CustomerContact {get; set;}
}

public class Address
{
  public Guid ID {get; set;}
  public Guid EnterpriseID {get; set;}
  public string Lines {get; set;}
}

我非常感谢有关如何配置它的建议。

The Enterprise table contains two Contacts, a PrimaryContact and a BillingContact.

那么EnterpriseContactAddress之间的关系应该是这样的:

public class Enterprise
{
    [Key]
    public Guid ID { get; set; }

    public Guid PrimaryContactId { get; set; }
    public Contact PrimaryContact { get; set; }

    public Guid BillingContactId { get; set; }
    public Contact BillingContact { get; set; }
}

public class Contact
{
    [Key]
    public Guid ID { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }

    public Address Address {get; set;}
}

public class Address
{
   [Key]
   public Guid ContactId {get; set;}
   public string Lines {get; set;}
}

然后在Fluent API配置中:

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

    modelBuilder.Entity<Enterprise>().HasOne(e => e.PrimaryContact)
            .WithOne()
            .HasForeignKey<Enterprise>(e => e.PrimaryContactId).OnDelete(DeleteBehavior.Restrict);

    modelBuilder.Entity<Enterprise>().HasOne(e => e.BillingContact)
            .WithOne()
            .HasForeignKey<Enterprise>(e => e.BillingContactId).OnDelete(DeleteBehavior.Restrict);

   modelBuilder.Entity<Contact>().HasOne(c => c.Address)
            .WithOne().HasForeignKey<Address>(a => a.ContactId);
}