1

I'm using MVC.net and I have 2 classes (case and accident) with a many to many relationship, I'm also using auto mapper to copy View Models to EF and vice versa. Now the problem i've come across is when i do this:

Case theCase = Mapper.Map<CaseEditVM, Case>(theCaseEditVM);
theCase.Accidents.Clear();
UOW.Cases.Update(theCase);

The changes to the case are saved but the link table for accidents is not. Ef totally ignores the Accidents changes.

However when i do:

Case theCase = UOW.Cases.GetByID(someid).Include("Accidents");
theCase.accidents.Clear();
UOW.Cases.Update(theCase);

EF correctly saves the accidents property.

So from what i can tell EF ignores the accident property as its not mapped inside EF yet. Make sense however how do i tell it when mapping the View model i want EF to update the linked properties as well?

Jammy
  • 779
  • 2
  • 13
  • 26

1 Answers1

0

The simplest way in your case is first attach case to context and clear changes after you attached it. Otherwise you will have a lot of work. There is no magic which would make this for you. EF doesn't know about changes to relations you did on detached entity and what is even worse once you attach the entity to context you already don't know what records were included in the navigation property so you cannot configure context to reflect that (it must be done per every single related entity) without reloading the whole entity and merging changes between detached and attached one.

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • I've tried dbSet.Attach(entityToUpdate); entityToUpdate.Accidents.Clear(); context.Entry(entityToUpdate).State = EntityState.Modified; But it wont clear the list. The only way i can get it to work is to Load the case with "Include" then make changes. However EF throws this exception "An object with the same key already exists in the ObjectStateManager" if i load the case then auto mapp the new values on to it. – Jammy Oct 06 '11 at 10:28
  • Scratch that i was using Case theCase = UOW.Cases.GetByID(theCaseEditVM.ID); theCase = Mapper.Map(theCaseEditVM); which gave the error but just noticed if i do Case theCase = UOW.Cases.GetByID(theCaseEditVM.ID); Mapper.Map(theCaseEditVM, theCase); EF is happy and the changes are copied. Woohoo. tnx – Jammy Oct 06 '11 at 10:35