[RESOLVED]Entity Framework updating many-to-many join table incorrectly

I have a ChangeRequest object and a BusinessArea object with a many-to-many relationship. There is a join table: ChangeRequestBusinessArea.

If I create and save a new ChangeRequest with BusinessAreaIDs 2,7,8 and 10, the join table updates just fine.

e.g.

ChangeRequestID BusinessAreaID
1 2
1 7
1 8
1 10

But when I then edit and save the same ChangeRequest with BusinessAreaIDs 1,2,3,7 and 10, I get the following:

ChangeRequestID BusinessAreaID
1 2
1 7
1 8
1 10
1 11
1 12
1 13
1 14
1 15

Here is the code:

Classes

namespace MOC.Models
{
    public class ChangeRequest
    {
        public ChangeRequest()
        {
            BusinessAreas = new List<BusinessArea>();
        }

        public int ChangeRequestID { get; set; }
        public string ChangeRequestName { get; set; }

        public virtual ICollection<BusinessArea> BusinessAreas { get; set; }
    }
}

namespace MOC.Models
{
    public class BusinessArea
    {
        public int BusinessAreaID { get; set; }
        public string BusinessAreaName { get; set; }

        public virtual ICollection<ChangeRequest> ChangeRequests { get; set; }
    }
}

Action Method

	 [HttpPost]
        public ActionResult Edit(int id, ChangeRequestViewModel ChangeRequestViewModel)
        {
            if (ModelState.IsValid)
            {
                var changeRequest = new ChangeRequest
                {
                    ChangeRequestID = id
                };

                AddOrUpdateBusinessAreas(changeRequest, ChangeRequestViewModel.BusinessAreas);
                db.Entry(changeRequest).State = EntityState.Modified;
                db.SaveChangeRequests();

                return RedirectToAction("Index");
            }
            return View(ChangeRequestViewModel);
        }

        private void AddOrUpdateBusinessAreas(ChangeRequest ChangeRequest, IEnumerable<AssignedBusinessAreaData> assignedBusinessAreas)
        {
            foreach (var assignedBusinessArea in assignedBusinessAreas)
            {
                if (assignedBusArea.Assigned)
                {
                    var busarea = new BusArea { BusAreaID = assignedBusArea.BusAreaID };
                    //db.BusAreas.Attach(busarea);
                    Change.BusAreas.Add(busarea);
                } else {
                    var busarea = new BusArea { BusAreaID = assignedBusArea.BusAreaID };
                    Change.BusAreas.Remove(busarea);
                }

            }
        }

Leave a Reply