我有一个关于如何使用Code First fluent API配置与一个连接表的一对多关系的问题。我有一个公司,联系对象都是共用一个地址对象像下面使用EF代码优先加入表与一对多关系
Class Address {
public int AddressId
.....
}
Class Company {
public int CompanyId
......
public virtual ICollection<Address> Address
}
Class Contact {
public int ContactID
.......
public virtual ICollection<Address> Address
}
我预计DB结构将是
Company Table
CompanyId PK NOT NULL
.....
Contact Table
ContactId PK NOT NULL
.....
Address Table
AddressId PK NOT NULL
.....
CompanyAddress Table
CompanyId NOT NULL
AddressId NOT NULL
ContactAddress Table
ContactId NOT NULL
AddressId NOT NULL
我可以通过使用下面的流畅API
实现这一目标modelBuilder.Entity<Company>()
.HasMany(c => c.Address)
.WithMany()
.Map(m =>
{
m => m.MapLeftKey("CompanyId")
.MapRightKey("AddressId")
.ToTable("CompanyAddress")});
modelBuilder.Entity<Contact>()
.HasMany(c => c.Address)
.WithMany()
.Map(m =>
{
m => m.MapLeftKey("ContactId")
.MapRightKey("AddressId")
.ToTable("ContactAddress")});
但EF开始将公司和地址视为多对多关系,当我尝试删除公司或联系人时,它不删除相应的地址记录(因为EF处理他们多到很多),我如何使用带级联删除选项的EF来定义这种类型的关系。我搜索了3天以上,惊讶没有人谈过或提出过这种情况,所以想知道我的方法是错误的还是答案很微不足道。
你的问题似乎是关于级联删除比许多一对多的关系,等等。也许问题的标题应该更像“我如何防止EF中的级联删除?” – 2013-04-05 00:53:25