【问题标题】:How do I configure navigation properties of varying multiplicity between two tables using fluent API如何使用 fluent API 在两个表之间配置不同多重性的导航属性
【发布时间】:2018-03-02 03:28:42
【问题描述】:

我是 Entity Framework 的新手,我正在尝试在 Code-First 项目中配置两个导航属性。

第一个属性是employee_pay_period(s) 的集合。每个employee_salary 有多个employee_pay_period(s),每个employee_pay_period 有一个employee_salary。

employee_pay_period.employee_salary_id 是外键。

第二个属性employee_salary.employee_current_pay_period 有点棘手。它是一个指向当前employee_pay_period 的属性。因此,导航属性从一个employee_salary 到一个employee_pay_period。数据库中没有与第二个属性关联的外键,每个employee_salary 必须包含一个employee_current_pay_period。

如何使用 fluent API 正确映射这些属性。

public class employee_salary
{
    public employee_salary()
    {
        employee_pay_period = new HashSet<employee_pay_period>();
    }

    [Key]
    public int employee_salary_id { get; set; }

    public int? employee_current_pay_period_id { get; set; }

    public virtual employee_pay_period employee_current_pay_period { get; set; }

    public virtual ICollection<employee_pay_period> employee_pay_period { get; set; }

}



public partial class employee_pay_period
{

    [Key]
    public int employee_pay_period_id { get; set; }

    public int employee_salary_id { get; set; }

    public virtual employee_salary employee_salary { get; set; }
}

【问题讨论】:

    标签: c# .net entity-framework ef-fluent-api


    【解决方案1】:

    如果我理解正确,您希望 employee_salaryemployee_pay_period 之间分别存在一对多的关系,而且 employee_salary 和当前 employee_pay_period 之间也是一对一关系

    OnModelCreating(ModelBuilder builder) 函数中是这样的(假设您已经设置了 fluentApi 上下文配置类的其余部分):

    builder.Entity<employee_salary>(e =>
    {
        e.HasMany(s => s.employee_pay_period) // salary has many pay periods
            .WithOne(p => p.employee_salary) // pay period has one salary
            .HasForeignKey(p => p.employee_salary_id) // foreign key on pay period linking to a single salary id
            .OnDelete(DeleteBehavior.Restrict); // Or whatever the desired delete behaviour should be
    
        e.HasOne(s => s.employee_current_pay_period) // salary has one current pay period
            .WithOne(p => p.employee_salary) // pay period has one salary
            .HasForeignKey<employee_salary>(s => s.employee_current_pay_period_id) // foreign key on salary linking to a single current pay period id
            .OnDelete(DeleteBehavior.Restrict); // Or whatever the desired delete behaviour should be
    }
    

    【讨论】:

    • employee_current_pay_period_id 在实际数据库中不是外键有关系吗?这会导致问题吗?
    • 我也在使用 EF 6.2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多