c# - 使用 EF 6.0 和代码优先的一对一 EntityTypeConfiguration
问题描述
我想使用 EF 6、代码优先和流畅的配置创建一对一的关系。我只想要根目录中的导航属性。这可能吗?如果是这样,我该如何配置我的EntityTypeConfigurations
?我需要更改SalarayId
为EmployeeId
吗?
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public virtual Salary Salary {get; set; }
}
public class Salary
{
public int SalaryId { get; set; }
public double Amount { get; set; }
}
public class EmployeeConfiguration : EntityTypeConfiguration<Employee>
{
public EmployeeConfiguration()
{
HasKey(e => e.EmployeeId);
}
}
public class SalaryConfiguration : EntityTypeConfiguration<Salary>
{
public SalaryConfiguration()
{
HasKey(s => s.SalaryId);
}
}
解决方案
是的。EF6 中的一对一关系基于两个表之间的 PK。PK 的名称不需要匹配,但通常最好在查看数据时避免混淆。
对于 EntityTypeConfiguration,只需从引用另一个对象的一侧进行设置,在本例中为 Employee:
public EmployeeConfiguration()
{
HasKey(e => e.EmployeeId);
HasRequired(e => e.Salary) // or HasOptional if salary is optional on Employee
.WithRequired(); // no back reference.
}
EF应该通过每张桌子上的PK把这些结合起来。
希望薪水不仅仅包括关键和金额。就目前而言,这是不必要的标准化。一对一的关系可以很好地适应昂贵的和/或不经常使用的数据列之类的东西。(即图像或大文本) 从绩效和存储的角度来看,将薪水作为员工的双/十进制更有效。
推荐阅读
- scala - 类型参数 [Nothing,X] 不符合类型参数界限 [T,X<: XX[T]]>
- android - 长按动作的搜索栏
- java - 如何使用 Java 使已生成的现有 JWT 令牌过期?
- elasticsearch - 如何从 OpenShift EFK 堆栈中的日志条目中提取和可视化值
- google-cloud-platform - 我不确定这是否是 Cloud Pub/Sub 内部错误
- javascript - 在页面开头由 foreach 生成的文本选项中插入“列表继续”之类的文本
- javascript - 如何为 Google Apps 脚本编写适当的文档?
- python - 导入 python 包时的语法错误
- javascript - 如何使必填字段动态反应?
- reactjs - 如何在 React js 中将部分输入与正则表达式匹配?