我一直试图使用fluent api为下面的图像配置适当的映射。(如果有人标记为副本,为了所有神圣的爱,请包括相关链接!)我花了好几天时间梳理堆积如山。

我的一个主要想法是,所有实体都将拥有一个EnterpriseID,它将用作切分键。
企业表包含两个联系人,一个PrimaryContact和一个BillingContact。
我想要做的是创建一个新的企业,其中包含一个代码生成的GUID ID以及两个联系人(主联系人和账单),将企业 ID分配给这些联系人,并在对象层次结构上调用SaveChanges (此时是企业->联系人->地址)。
没有任何流畅的映射,EF核心 2.1说..。“‘联系人’和'Enterprise.BillingContact‘之间的关系以及’联系人‘与'Enterprise.PrimaryContact’之间的关系都可以使用Enterprise.BillingContact作为外键。要解决这个问题,至少要在其中一个关系上显式地配置外键属性。”
我尝试过许多配置,要么使用只定义了Enterprise表中的一个联系人属性的DB,要么将整个混乱转移到FK /循环地狱中。
下面是当前的类存根。
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;}
}我非常希望能就如何配置这个问题提供一些建议。
发布于 2019-07-20 03:41:55
企业表包含两个联系人,一个PrimaryContact和一个BillingContact。
那么Enterprise、Contact和Address之间的关系应该如下:
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);
}https://stackoverflow.com/questions/57119591
复制相似问题