Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 803
t_plusplus Avatar asked Nov 08 '13 17:11

t_plusplus


1 Answers

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; }
like image 154
Ilya Avatar answered Sep 27 '22 16:09

Ilya