我有具有多对多关系的 Book 和 Author 实体,我正在尝试使用数据库优先方法保存关系(联结表中的记录)。
我想从我的工作版本代码开始
[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");
}
在上面的代码中,我从数据库中获取作者对象(记录)以添加与书籍对象的关系。然而,我不是从数据库中获取 Book 对象,而是将其附加到上下文中。我不能对 Author 对象做类似的事情吗?
我尝试使用此代码执行此操作,但它首先将新记录添加到作者表并添加与书籍和新创建的(不需要的)作者的关系:
[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");
}