Reputation: 1
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?
Upvotes: 0
Views: 316
Reputation: 364409
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);
}
Upvotes: 3
Reputation: 32596
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
}
Upvotes: 4