代码优先实体框架 - 同一表的多个外键
问题描述:
我有一个假日
表和一个用户
表。
假期
表有列 RequesterID
和 AuthorisedByID
,它们链接到用户
表的主键。
The Holiday
table has columns RequesterID
and AuthorisedByID
, which both link to the primary key of the User
table.
这是我的假期
模型:
public class Holiday
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid HolidayId { get; set; }
[ForeignKey("UserId")]
public virtual User User { get; set; }
public Guid RequesterId { get; set; }
public Guid? AuthorisedById { get; set; }
}
我无法声明 AuthorisedByID
作为用户表中的外键,就像我以前一样,使用
RequesterId
列。
我想知道你能给我一些关于如何解决的提示。
I wonder if you can give me some hints on how to resolve.
谢谢。
答
代码首先不能自行匹配两个类中的属性。
Code first is not able to match up the properties in the two classes on its own.
要解决这些问题,您可以使用InverseProperty注释来指定属性的对齐。
To fix these problems, you can use the InverseProperty annotation to specify the alignment of the properties.
[ForeignKey("RequesterUser")]
public Guid RequesterId { get; set; }
[ForeignKey("AuthorisedUser")]
public Guid AuthorisedById { get; set; }
[InverseProperty("RequesterHoliday")]
public virtual User RequesterUser{ get; set; }
[InverseProperty("AuthorisedHoliday")]
public virtual User AuthorisedUser{ get; set; }
public List<Holiday> RequesterHoliday { get; set; }
public List<Holiday> AuthorisedHoliday{ get; set; }