1

I am designing a code-fire migration using Entity Framework and have some problem when one object has a List of the same type as itself. Say I have a User object which has a List<User> as its Friends:

public class User
{
    [Key]
    public int UserId { get; set; }

    // some other stuff

    public List<User> Friends { get; set; }
}

The problem is EF looks for a foreign key for the User and tries to create one when it couldn't find any:

AddColumn("dbo.Users", "User_UserId", c => c.Int());

I am trying to avoid making UserId a key and foreign key at the same time, so what's a good practice here?

Yar
  • 7,020
  • 11
  • 49
  • 69
  • 1
    `UserId` can't be a foreign key, it's a one-to-many relationship. You'll need a separate friend-of-user table, with entries connecting user id to its friend ids. – Sergey Kalinichenko Feb 10 '17 at 02:09
  • 1
    You need to have separate tables for both Friends and Users. In your case, Entity framework is trying to figure out the foreign key for to build relationship. And it finds the UserId from same table which is unique primary key. You can not avoid it. – Pavvy Feb 10 '17 at 05:14

2 Answers2

1

A separate table would be best here.

Name: UserFriend PK: UserFriendId FK: UserId FK: FriendId

Shane Ray
  • 1,449
  • 1
  • 13
  • 18
-2

You can't use List<T> for a related collection in Entity Framework. It must be virtual ICollection<T>.

Yar
  • 7,020
  • 11
  • 49
  • 69
Jason Lind
  • 263
  • 1
  • 2
  • 15