0

I'm trying to come up with a model for managing Person and its Friends.

  • A Person has 0-to-many Friends
  • A Friend is a Person too - not the same one though
  • A Friend can belong one or more Groups

Roughly, the schema looks something like this:

enter image description here

I cannot figure out how to achieve the same with EF Code First. This is what I have so far but this doesn't create the required schema

public class Person 
{
    public long Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public virtual ICollection<Person> Friends { get; set; } // is this right?
}

public class Friend {
    public long Id { get; set; }
    public long PersonId { get; set; }  // Person whose Friend this guy is
    public virtual ICollection<Group> Groups { get; set; } 

    // other fields 
}

public class Group{
    public long Id { get; set; }
    public string Name { get; set; }
}

Can someone help me figure out this mess?

Mrchief
  • 75,126
  • 20
  • 142
  • 189

1 Answers1

3

You need self referencing many-to-many relation on Person because you current model allows each person to have many friends but in the same time each person can be friend with only one other person.

Try this:

public class Person 
{
    public long Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public virtual ICollection<Person> FriendWith { get; set; } 
    public virtual ICollection<Person> FriendOf { get; set; } 
}

And you can add this fluent-API mapping:

modelBuilder.Entity<Person>()
            .HasMany(p => p.FriendWith)
            .WithMany(p => p.FriendOf)
            .Map(m => {
                 m.MapLeftKey("PersonId");
                 m.MapRightKey("FriendId");
                 m.ToTable("PersonFriends");
            });

It may seem strange but associations in EF builds oriented graph => if a person A is friend with a person B it is considered as different relation then if a person B is friend with a person A. One of these relations will be in FriendWith collection and another will be in FriendOf collection.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670