【问题标题】:Code-first Entity Framework - Multiple Foreign Keys For the Same Table代码优先实体框架 - 同一个表的多个外键
【发布时间】:2013-11-20 19:29:35
【问题描述】:

我有一个Holiday 表和一个User 表。

Holiday 表有 RequesterIDAuthorisedByID 列,它们都链接到 User 表的主键。

这是我的Holiday 模特:

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; }
}

我无法在 User 表中将 AuthorisedByID 声明为外键,就像我对 RequesterId 列所做的那样。

我想知道你能否给我一些关于如何解决的提示。

谢谢。

【问题讨论】:

    标签: entity-framework ef-code-first entity-framework-migrations


    【解决方案1】:

    代码优先无法单独匹配两个类中的属性。

    要解决这些问题,可以使用 InverseProperty 注解来指定属性的对齐方式。

    [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; }
    

    【讨论】:

    • 这确实需要清理。复数集合名称等。这应该是两个单独的表吗?因为那还不清楚。
    猜你喜欢
    • 2011-07-30
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多