0

I am trying to use EF Code first to create a database but I am not sure how to define the classes for the following relationship so that it is efficient.

We have a User and User has Friends, which in turn is a collection of User, so I was thinking of the following POCO Class

`//Class User
public class User
{
  public Guid UserId{get;set;}
  public string UserName{get;set;}
  public String UserAddress{get;set;}
  // other user properties
}

//Class Friend
public class Friend
{ 
  public Guid FriendId{get;set;} //unique identifier for Friend Table
  public virtual User CurrentUser{get;set;}
  public List<User> lstUserFriends {get;set;} //contains list of all friends that the     user has

}`

Does this look good performance-wise or do you think you can suggest an alternative?

1
  • 3
    It looks a bit strange to me... What is Friend? What not make "Friends" a property of User? (self referencing foreign key) Commented May 6, 2011 at 1:56

2 Answers 2

4

Why not just do

public class User
{
  public Guid UserId{get;set;}
  public string UserName{get;set;}
  public String UserAddress{get;set;}
  public IList<User> Friends{get;set;}
  // other user properties
}
Sign up to request clarification or add additional context in comments.

1 Comment

This seems to be only create one to one relation ship between each user as it has MembermemberId column created on each member row within the same table.
3

You need self referencing many-to-many relation because use can have many friends but also can be friend of many users.

public class User
{
    public Guid UserId { get; set; }
    public string UserName { get; set; }
    public String UserAddress { get; set; }

    [InverseProperty("Friends")]
    public virtual ICollection<User> FriendWith { get; set; }
    [InverseProperty("FriendWith")]
    public virtual ICollection<User> Friends { get; set;} 
}

Or you can omit InverseProperty data annotation and use fluent mapping:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>()
                .HasMany(u => u.Friends)
                .WithMany(f => f.FriendWith);
    // I'm not sure but you can also need to add this:
    //          .WillCascadeOnDelete(false);
}

1 Comment

Excellent answer, you just saved me a couple of hours.

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.