Willy
Willy

Reputation: 3824

EF CodeFirst creating additional Column don't understand why

I got a class "Friend"

    public class Friend
{
    [Key , Column(Order = 0)]
    public string MeID { get; set; }

    public ApplicationUser Me { get; set; }

    [Key, Column(Order = 1)]
    public string MyFriendID { get; set; }

    public ApplicationUser MyFriend { get; set; }

    public bool isFavorite { get; set; }
}

when creating the database , It adds an additional column "ApplicationUser_Id" , anyone got a reasonable explanation for why is it doing that ?

i'm sorry if it's a beginners question.

thanks in advance.

Upvotes: 0

Views: 48

Answers (2)

oryol
oryol

Reputation: 5248

Add [ForeignKey("MyFriendID")] attribute to MyFriend property and [ForeignKey("MeID")] to Me property

If you use C# 6 you can use nameof(MyFriendID) instead of hard-coded string "MyFriendID" (suggested by @TGlatzer)

Upvotes: 0

Zein Makki
Zein Makki

Reputation: 30052

It is a relationship column. Friend has-a ApplicationUser. So for that relationship to be implemented, the database table Friend has to have a foreign key ApplicationUser_Id which is the Primary Key for type ApplicationUser.

To get rid of that column, you can use the [NotMapped] attribute:

[NotMapped]
public ApplicationUser MyFriend { get; set; }

Upvotes: 1

Related Questions