EF ObservableListSource指定ForeignKey

时间:2013-03-08 09:40:43

标签: c# entity-framework entity-framework-4 ef-code-first entity-framework-4.1

我有两个实体:Employee& Contract

Contract实体中,我拥有属性AddedByEmployee& AssignedToEmployee

我想在Employee课程中使用集合导航属性,但如何在Contract课程中引用正确的密钥?

到目前为止,我有:

public class Employee
{
    public int EmployeeID {get; set;}
    public string Name {get; set;}
    private readonly ObservableListSource<Contract> _Contracts = new ObservableListSource<Contract>();
    public virtual ObservableListSource<Contract> Contracts { get { return _Contracts; }
}

public class Contract
{
    public int ContractID {get; set;}
    public string Name {get; set;}
    public int AddedByEmployeeID {get; set;}
    public int AssignedToEmployeeID {get; set;}

    [ForeignKey("AddedByEmployeeID")]
    public virtual Employee AddedByEmployee { get; set; }

    [ForeignKey("AssignedToEmployeeID")]
    public virtual Employee AssignedToEmployee { get; set; }
}

基本上如此:我如何让ObservableListSource<Contract>知道它是我要映射到的AddedByEmployeeID

由于

1 个答案:

答案 0 :(得分:0)

您可以使用DataAnnotations或Fluent API执行此操作。

使用DataAnnotations执行此操作,您可以将InverseProperty属性添加到ContractsAddedByEmployee属性(或两者兼有,但这不是必需的)。

这会告诉Entity Framework应该在ContractsAddedByEmployee之间建立关系。

[InverseProperty("AddedByEmployee")]
public virtual List<Contract> Contracts
{
    get { return _Contracts; }
}

如果您想使用Fluent API,您只需要明确定义这样的关系:

modelBuilder.Entity<Employee>()
    .HasMany(p => p.Contracts)
    .WithRequired(p => p.AddedByEmployee)