QBM5 QBM5 - 5 months ago 31
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{
public int UserId {get; set;}
public string Username {get; set;}
public virtual List<Room> Rooms {get; set;}

public class Room{
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

.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.



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
    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:

    .HasMany(u => u.OwnerOfRooms)
    .WithRequired(r => r.Owner)
    .HasForeignKey(r => r.OwnerId);

    .HasMany(u => u.MemberOfRooms)
    .WithMany(r => r.Members);

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