QBM5 QBM5 - 1 month ago 6
C# Question

Entity framework issues when I need to have multiple relations of the same type

This issue has been dogging me for a while, and would appreciate any help

Lets say I have two classes, users and room, that basically go like this

public class User{
[Key]
public int UserId {get; set;}
public string Username {get; set;}
public virtual List<Room> Rooms {get; set;}
}

public class Room{
[Key]
public int RoomId {get; set;}
[ForeignKey("Owner")] // have tried with and without the explicit relationship
public int OwnerId {get; set;}
public User Owner {get; set; }
public virtual List<User> Members {get; set;}
}


My hope is to build s structure that allows a user to have multiple rooms where they are the owner, but also be included into multpiple rooms as a member.

the problem comes when I actually try to make a room and add the memebers. The owner properties are added, but the Members list is always empty.

I'm using the annotation API, but have also tried the fluent API

When I try this, I get a multiplicity error

modelBuilder.Entity<Room>()
.HasMany(t => t.Members).WithMany(u => u.Rooms);


I am sure the answer is simple, I am just not that good with entity. Any help would be appreciated.

Thanks

Answer

You have two relationships between User and Room:

  • Rooms where user is the owner (one-to-many)
  • Rooms where user is a member (many-to-many)

Single Rooms collection cannot represent the two relationships, you need two collections:

public class User
{
    [Key]
    public int UserId {get; set;}
    public string Username {get; set;}
    public virtual List<Room> OwnerOfRooms {get; set;}
    public virtual List<Room> MemberOfRooms {get; set;}
}

and use the following Fluent configuration:

modelBuilder.Entity<User>()
    .HasMany(u => u.OwnerOfRooms)
    .WithRequired(r => r.Owner)
    .HasForeignKey(r => r.OwnerId);

modelBuilder.Entity<User>()
    .HasMany(u => u.MemberOfRooms)
    .WithMany(r => r.Members);

Note that the second relationship will create automatic junction table UserRooms.