代码优先实体框架 - 同一表的多个外键 [英] Code-first Entity Framework - Multiple Foreign Keys For the Same Table

查看:247
本文介绍了代码优先实体框架 - 同一表的多个外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个假日表和一个用户表。

假期表有列 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; }

这篇关于代码优先实体框架 - 同一表的多个外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆