I have Book and Author entities with many to many relation and I am trying to save the relation (a record in junction table) with Database first approach.
I would like to start with my working version of code
[HttpPost]
public ActionResult Edit(BookViewModel bookv)
{
Mapper.CreateMap<AuthorViewModel, Author>();
List<Author> authors = Mapper.Map<List<AuthorViewModel>, List<Author>>
(bookv.Authors.ToList());
//remove authors from book object to avoid multiple entities with same key error
bookv.Authors.Clear();
Mapper.CreateMap< BookViewModel,Book>();
Book book = Mapper.Map<BookViewModel,Book>(bookv);
db.Books.Attach(book);
book.Authors.Clear();
foreach (Author a in authors)
{
//Fetch Author and add relation to book object
book.Authors.Add(db.Authors.Single(at=>at.AuthorId==a.AuthorId));
}
db.ObjectStateManager.ChangeObjectState(book, EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
In above code, I am fetching Author object (record) from database to add relation with book object. Whereas,I am not fetching Book object from database but attaching it to the context. Can't I do something similar with Author objects?
I have tried to do this with this code but it first adds new records to Author table and adds relation with book and newly created (unwanted) authors:
[HttpPost]
public ActionResult Edit(BookViewModel bookv)
{
Mapper.CreateMap<AuthorViewModel, Author>();
List<Author> authors = Mapper.Map<List<AuthorViewModel>, List<Author>>(bookv.Authors.ToList());
// bookv.Authors.Clear();
Mapper.CreateMap< BookViewModel,Book>();
Book book = Mapper.Map<BookViewModel,Book>(bookv);
foreach (Author a in book.Authors)
{
db.Authors.Attach(a);
}
db.Books.Attach(book);
foreach (Author a in authors)
{
book.Authors.Add(a);
}
db.ObjectStateManager.ChangeObjectState(book, EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}