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我想要映射到的?

谢谢

4

1 回答 1

0

您可以使用DataAnnotationsFluent API 或 Fluent API 来做到这一点。

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

这将说明Entity Framework应该在Contracts和之间建立关系AddedByEmployee

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

如果您想改用 Fluent API,您只需像这样显式定义关系:

modelBuilder.Entity<Employee>()
    .HasMany(p => p.Contracts)
    .WithRequired(p => p.AddedByEmployee)
于 2013-03-08T17:39:23.017 回答