7

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 Answer 1

9

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; }
Sign up to request clarification or add additional context in comments.

1 Comment

This really needs to be cleaned up. Pluralize the collection names, etc. Is this supposed to be two separate tables? Because that isn't clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.