Jed Grant
Jed Grant

Reputation: 1425

Build a model with 2 Foreign Keys to the Same Table

Lets say I have a User model and now I want to add a Friend model. I want to name my FK fields RequestorID and ResponderID. What data annotations or fluent api mappings do I need to accomplish this and prevent EF from autogenerating its own columns?

public class Friend
{
    public int FriendID { get; set; }
    public int RequestorID { get; set; }
    public int ResponderID { get; set; }
    public int FriendStatusID { get; set; }
    public DateTime User1RequestDate { get; set; }
    public DateTime User2ResponseDate { get; set; }
    public virtual FriendStatus FriendStatus { get; set; }


    public virtual User Requestor { get; set; }
    public virtual User Responder { get; set; }

}

Upvotes: 1

Views: 65

Answers (1)

WannaCSharp
WannaCSharp

Reputation: 1898

Try this

public class Friend
    {
        public int FriendID { get; set; }
        public int RequestorID { get; set; }
        public int ResponderID { get; set; }
        public int FriendStatusID { get; set; }
        public DateTime User1RequestDate { get; set; }
        public DateTime User2ResponseDate { get; set; }
        public virtual FriendStatus FriendStatus { get; set; }

        [ForeignKey("RequestorID")] //fixed
        public virtual User Requestor { get; set; }
        [ForeignKey("ResponderID")]
        public virtual User Responder { get; set; }
    }

Upvotes: 2

Related Questions