EF ObservableListSource Specify ForeignKey
本文关键字:ForeignKey Specify ObservableListSource EF | 更新日期: 2023-09-27 18:02:49
我有两个实体: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
?
谢谢
您可以通过使用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)