我不知道,如果你想以下几点:
modelBuilder.Entity<Customers>()
.HasMany(c => c.Phones)
.WithOptional()
.Map(m => m.MapKey("CustomerPhoneId"));
modelBuilder.Entity<Companies>()
.HasMany(c => c.Phones)
.WithOptional()
.Map(m => m.MapKey("CompanyPhoneId"));
使用MapKey
是可选的。它只是给外键列一个你想要的名字。如果您省略此EF将创建一个标准名称(与下划线:..._Id
)。
事实上,整个映射是可选的,因为映射约定只会在没有任何Fluent API映射的情况下创建相同的关系。
的Phones
表将有两个空的外键CustomerPhoneId
分别CompanyPhoneId
指的Customers
表和Companies
表。
编辑
一种替代这将只需要在Phone
表针对多个不同实体一个外键将是一个继承映射:
public abstract class OrganizationsWithPhone
{
public OrganizationsWithPhone()
{
Phones = new List<Phones>();
}
public Guid Id { get; set; }
public ICollection<Phones> Phones { get; set; }
}
public class Customers : OrganizationsWithPhone
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Companies : OrganizationsWithPhone
{
public string Name { get; set; }
}
public class Phones
{
public Guid Id { get; set; }
public string Number { get; set; }
public string Extension { get; set; }
}
映射:
modelBuilder.Entity<OrganizationsWithPhone>()
.HasMany(o => o.Phones)
.WithOptional() // or .WithRequired()
.Map(m => m.MapKey("OrganizationsWithPhoneId"));
modelBuilder.Entity<OrganizationsWithPhone>()
.ToTable("OrganizationsWithPhone");
modelBuilder.Entity<Customers>()
.ToTable("Customers");
modelBuilder.Entity<Companies>()
.ToTable("Companies");
现在你只有一个Phones
和ba之间的外键关系se表OrganizationsWithPhone
,但由于继承映射关系,在派生实体Customers
和Companies
的基表和表格之间存在额外的一对一关系。基本上,必要关系的数量保持不变(或者在此模型中甚至更多)。
在这种模式下,客户和公司不能共享相同的电话号码,因为Phones
表中的一行指的是OrganizationsWithPhone
,它既可以是客户也可以是公司,但不能同时存在。
基表OrganizationsWithPhone
只有一列Id
。如果您在所有派生实体中具有更多通用属性,则可以将它们移动到基本实体中。
只有查克诺里斯能够掌握relanshioshio。 – Slauma 2012-03-25 15:29:20
抱歉,错字,请有效的评论,这会浪费我的时间。 – 2012-03-25 18:56:05
对不起,我无法抗拒:)这看起来不像是一个错字,而是一个巨大的错字集群。你可以回滚编辑?第一个版本更有趣。我现在提供了一个答案。 – Slauma 2012-03-25 19:37:17