我有两个实体: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
?
由于
答案 0 :(得分:0)
您可以使用DataAnnotations
或Fluent API执行此操作。
使用DataAnnotations
执行此操作,您可以将InverseProperty
属性添加到Contracts
或AddedByEmployee
属性(或两者兼有,但这不是必需的)。
这会告诉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)