Son*_*Sam 1 entity-framework-4.1
这是我的第一个问题,我希望不是一个愚蠢的问题.
我在这里有以下实体
客户公司电话
public class Customers
{
public Customers()
{
Phones = new List<Phones>();
}
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Phones> Phones { get; set; }
}
public class Phones
{
public Guid Id { get; set; }
public string Number { get; set; }
public string Extension { get; set; }
}
public class Companies
{
public Companies()
{
Phones = new List<Phones>();
}
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<Phones> Phones { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想用流畅的api创建手机之间的一对多关系,以及与公司和手机相同的关系.
我不确定您是否需要以下内容:
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"));
Run Code Online (Sandbox Code Playgroud)
使用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; }
}
Run Code Online (Sandbox Code Playgroud)
制图:
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");
Run Code Online (Sandbox Code Playgroud)
现在你只有一个外键关系Phones和基表OrganizationsWithPhone,但由于继承映射有基表和派生实体表之间增加一到一对一的关系Customers和Companies.基本上,必要关系的数量保持不变(或者在此模型中甚至更多).
在此模型中,客户和公司不能共享相同的电话号码,因为Phones表中的行指的OrganizationsWithPhone是可以是客户或公司但可以同时不是两者.
基表OrganizationsWithPhone只有一列Id.如果您在所有派生实体中有更多共同属性,则可以将它们移动到基本权限中.
| 归档时间: |
|
| 查看次数: |
9409 次 |
| 最近记录: |