Code-first Entity Framework - Multiple Foreign Keys For the Same Table

ef-code-first ef-migrations entity-framework

Question

I have a Holiday table and a User table.

The Holiday table has columns RequesterID and AuthorisedByID, which both link to the primary key of the User table.

This is my Holiday model:

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

I am unable to declare the AuthorisedByID as a foreign key in the User table just like I think I did with RequesterId column.

I wonder if you can give me some hints on how to resolve.

Thanks.

1
7
11/8/2013 5:28:17 PM

Accepted Answer

Code first is not able to match up the properties in the two classes on its own.

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; }
9
11/8/2013 5:45:15 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow