【问题标题】:Can you use navigation sub-properties in foreign keys using EF 4.1 fluent API?您可以使用 EF 4.1 fluent API 在外键中使用导航子属性吗?
【发布时间】:2011-05-20 13:06:52
【问题描述】:

让我们用一个简单的例子:

public class Employee
{
    public int EmployeeID { get; set; }
    public ICollection<Pay> Pays { get; set; }
}

public class Pay
{
    public Employee Employee { get; set; }
    public int Year { get; set; }
    public double Amount { get; set; }
}

有什么方法可以使用 fluent API 创建一个主键为 Employee_EmployeeID, Year 的 Pays 表(使用 EF4.1 列约定)?

我不想使用数据注释,但我还是尝试了这个:

public class Pay
{
    [Key, Column(Order = 0)]
    public Employee Employee { get; set; }
    [Key, Column(Order = 1)]
    public int Year { get; set; }
    public double Amount { get; set; }
}

我得到的只是Year 上的主键和Employee_EmployeeID 上的外键。

【问题讨论】:

    标签: entity-framework-4.1 fluent-interface


    【解决方案1】:

    这只有在您将 FK 属性添加到您的 Pay 时才有可能:

    public class Pay
    {
        public int EmployeeId { get; set; }
        public Employee Employee { get; set; }
        public int Year { get; set; }
        public double Amount { get; set; }
    }
    

    现在您可以使用 fluent-api 进行映射:

    modelBuilder.Entity<Pay>()
                .HasKey(p => new 
                    {
                        p.EmployeeId,
                        p.Year
                    });
    

    如果您想让员工的 FK 成为 PK 的一部分,您需要将其作为属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多