首页 > 解决方案 > 使用 EF 6.0 和代码优先的一对一 EntityTypeConfiguration

问题描述

我想使用 EF 6、代码优先和流畅的配置创建一对一的关系。我只想要根目录中的导航属性。这可能吗?如果是这样,我该如何配置我的EntityTypeConfigurations?我需要更改SalarayIdEmployeeId吗?

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);
    }
}

标签: c#entity-frameworkentity-framework-6ef-code-first

解决方案


是的。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把这些结合起来。

希望薪水不仅仅包括关键和金额。就目前而言,这是不必要的标准化。一对一的关系可以很好地适应昂贵的和/或不经常使用的数据列之类的东西。(即图像或大文本) 从绩效和存储的角度来看,将薪水作为员工的双/十进制更有效。


推荐阅读