简体   繁体   中英

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");
    });

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM