LueTm
LueTm

Reputation: 2380

Entity Framework Code First Many to Many Relationship with Existing Entities

I have the following situation:

modelBuilder.Entity<RecurringAppointment>()
    .HasMany(ra => ra.StaffMembers)
    .WithMany();

So a staff member (inherited from user) can have many recurring apointments and vice versa. Now, when I try to add staff members to recurringAppointment.StaffMembers like this ...

[Invoke]
public void ApplyStaffMembersToRecurringAppointment(int recurringAppointmentId, int[] staffMemberIds)
{
    var staffs = DbContext.Users
        .OfType<Staff>()
        .Where(s => staffMemberIds.Contains(s.Id))
        .ToList();

    var recurringAppointment = DbContext.RecurringAppointments
        .Include("StaffMembers")
        .Single(ra => ra.Id == recurringAppointmentId);

    foreach (var staff in staffs)
    {
        recurringAppointment.StaffMembers.Add(staff);
        DbContext.Users.Attach(staff);
    }

    DbContext.RecurringAppointments.Attach(recurringAppointment);
    DbContext.Entry(recurringAppointment).State = EntityState.Modified;
    DbContext.SaveChanges();
}

... it just won't save the changes. When I add values manually to the database it works perfectly, so the relation should be set up correctly.

I looked at tons of similar entries, but they all either didn't save or didn't attach. The code gets executed (I can debug). What could be the problem?

Upvotes: 1

Views: 890

Answers (1)

Mark Oreta
Mark Oreta

Reputation: 10416

Does your Staff Object have a navigation collection referring back to your Recurring appointment? When I had nav collections on both ReccuringAppointments and StaffMembers, the above code did not save changes.

If you only have the navigation collection on ReccuringAppointmets however it did work - unless I had set AutoDetectChangesEnabled = false in my configuration.

If neither of these cases happened, the code worked perfectly - if these cases aren't true for you, can you post your context/entities for more information?

Upvotes: 1

Related Questions