您可以使用EF 4.1 fluent API在外键中使用导航子属性吗?

时间:2011-05-20 13:06:53

标签: entity-framework-4.1 fluent-interface

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

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

有没有办法使用流畅的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上的外键。

1 个答案:

答案 0 :(得分:0)

只有在您向Pay添加FK属性时才会这样做:

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的一部分,你需要员工的FK。