我试图使用单个Address
表来存储具有通用KeyId
字段的系统中多个实体的地址。客户可以拥有多个地址,而供应商可以拥有多个地址。用于存储实体框架中许多实体(使用双重外键)地址的单个地址表
地址类:
public int Id { get; set; }
public string Name { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string ZipCode { get; set; }
// These 2 fields make it so I can get all of the addresses for a single Customer or Vendor
public string EntityType { get; set; }
public int KeyId { get; set; }
// Navigation properties
public Customer Customer { get; set; }
public Vendor Vendor { get; set; }
public Location Location { get; set; }
客户类:
public int Id { get; set; }
public string Name { get; set; }
// Navigation properties
public IList<Address> Addresses { get; set; }
供应商类:
public int Id { get; set; }
public string Name { get; set; }
// Navigation properties
public IList<Address> Addresses { get; set; }
的DbContext:
builder.Entity<Customer>()
.HasMany(c => c.Addresses)
.WithOne(a => a.Customer)
.HasForeignKey(a => a.KeyId);
builder.Entity<Vendor>()
.HasMany(v => v.Addresses)
.WithOne(a => a.Vendor)
.HasForeignKey(a => a.KeyId);
当试图种子数据库(添加了几个地址沿供应商),我遇到了,上面写着以下内容的错误:
SQLEXCEPTION:MERGE语句冲突与FOREIGN KEY约束“FK_Address_Customer_KeyId”。数据库“MyDatabase”中出现冲突,表“dbo.Customer”,列'Id'。
我敢肯定这是因为参照完整性说有是与您试图在KeyId
存储标识数据库中没有客户。
是否有任何可能的方式做这样的事情瓦特/ FluentAPI使用EF还是我在玩火?它只是似乎很疯狂不得不创建一个名为CustomerAddress
和VendorAddress
,如果所有属性都是同一类。这几乎就像我需要指定EF不允许你做的双重外键。
附加说明:我想我会尝试,并设置一切SQL Management Studio中,然后在Visual Studio中添加数据库第一EF项目。我很好奇,看看它将如何创建模型和数据库上下文。
我知道你在以后被称为复合型EF –
@Chef_Code复杂类型是不是我想要的这里。它不适用于客户可以拥有多个地址且供应商可以拥有多个地址的一对多关系。 –