I am working on Database first approach with Entity Framework 4.1. I have 2 many to many related entities Book and Library. I also have one junction table with 10 columns to store information about the particular copy of the book in Library with one to many relation with both BOOK and LIBRARY entities. I have created a view which submits a JSON object with child object in it which matches the definition of my BookVieMOdel. The view is working just fine but I am having trouble adding new entries to the junction table in the controller. I am getting error saying "Adding a relationship with an entity which is in the Deleted state is not allowed".
I guess the error is referring to the deleted object which were deleted when by the book.LibraryBookCopies.Clear();
but can't think of doing it other way.
Thanks,
CONTROLLER:
[HttpPost]
public ActionResult Edit(BookViewModel bookv)
{
Mapper.CreateMap< BookViewModel,Book>();
Book book = Mapper.Map<BookViewModel,Book>(bookv);
db.Books.Attach(book);
db.ObjectStateManager.ChangeObjectState(book, EntityState.Modified);
//Add library ref to each libraryBookCopies object in Book
foreach (LibraryBookCopy lBC in book.LibraryBookCopies)
{
lBC.Library = db.Libraries.Single(l => l.LibraryId == lBC.LibraryId);
}
//Remove all currently related records
book.LibraryBookCopies.Clear();
//Add copies from ViewModel to book object
foreach (LibraryBookCopy lBC in bookv.LibraryBookCopies)
{ book.LibraryBookCopies.Add(lBC); //Error here }
db.SaveChanges();
return RedirectToAction("Index");
}