Entity Framework 6 Code First lookup table not populating

public class Profile
{
    public int Id { get; set; }
    //...
    public virtual List<Room> Rooms { get; set; }
}

public class Room
{
    public int Id { get; set; }
    //...
    public virtual List<Profile> Members { get; set; }
}

public void AddUserToRoom(Profile user, Room room)
{
    room.Members.Add(user);
    user.Rooms.Add(room);
    _DBContext.SaveChanges();
}

The above code generates the displayed schema, but the table ProfileRooms does not populate the ProfileRooms table after SaveChanges(). Then if queried afterwards the lists are blank. Someone catching what I'm doing wrong for the many to many mapping? AddUserToRoom is in a manager class that holds scope for the database context until dispose, so the context is still in scope at the time of the call. I have also overridden Profile and Room's Equals() and check against the ID's for equality.

  • .NET 4.5
  • MVC 5 project
  • IDE VS 2013

I'm obviously missing something. Thanks ahead of time!

--Updated-- Sorry, left out fluent api calls, which is probably where the fault lies:

modelBuilder.Entity<Room>()
    .HasMany(e => e.Members)
    .WithMany(a => a.Rooms)
    .Map(mc =>
    {
        mc.ToTable("RoomMembers");
        mc.MapLeftKey("RoomId");
        mc.MapRightKey("MemberId");
    });

modelBuilder.Entity<Profile>()
    .HasMany(e => e.Rooms)
    .WithMany(a => a.Members)
    .Map(mc =>
    {
        mc.ToTable("RoomMembers");
        mc.MapLeftKey("MemberId");
        mc.MapRightKey("RoomId");
    });

Answers


Solution

The room was retrieved from a different dbcontext in the manager. There was a static function to retrieve the room, then it was passed back in and the instance dbcontext was used to save changes. It had been awhile since the static method had been written and I had forgotten about it. Funny there was no error, it just went went through it with no changes. When I used the id from the passed in room to retrieve it from the class instance context, it worked.

--Additional Information for internet searchers--

I removed the virtual keyword from collections and also added a call to like:

_DbContext.Entry(room).Collection("Members").Load();

before removing items in the join table.


Need Your Help

String split in LINQ to Entities

c# asp.net entity-framework linq-to-entities

I have a table that contains a list of pagehits that I would like to analyse. One of the fields is URL that unsurprisingly contains the URL of the pagehit. This includes any query strings, e.g. htt...

How can I resolve out of memory error in MATLAB?

matlab

I want to calculate 2 covariance matrices with size (10304,1034) and matlab creates the first one but when it runs the second command, this error occurs: