我已经看到一些与主题相关的问题,但无法找到针对此方案的答案。在不加载实体的情况下更新ASP.NET MVC + EF4中的相关实体的最佳实践
我有一个像我的控制器
//
// GET: /Person/Edit/5
public ActionResult Edit(int id)
{
var viewModel = new PersonViewModel(PersonRepository.Get(id));
return View(model);
}
//
// POST: /Person/Edit
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(PersonViewModel model)
{
PersonRepository.Update(model.Person, model.Phones);
return RedirectToAction("Index");
}
的
部分在我的仓库IM结构做这样的事情:
public void Update(Person person, ICollection<Phone> phones)
{
using (var unitOfWork = UnitOfWork.Current)
{
Attach(contact);
UpdatePhones(contact, phones);
unitOfWork.Commit();
}
}
public Person Attach(Person person)
{
Context.AttachTo("Persons", entity);
Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
return entity;
}
public void UpdatePhones(Person person, ICollection<Phone> phones)
{
if (phones == null || phones.Count == 0) return;
foreach (var phone in phones.Where(o => o.IsDeleted && !o.IsNew))
{
PhoneRepository.Delete(phone);
}
foreach (var phone in phones.Where(o => !o.IsDeleted && o.IsNew))
{
party.Phones.Add(phone);
}
foreach (var phone in phones.Where(o => !o.IsDeleted && !o.IsNew))
{
phone.PartyID = party.ID;
PhoneRepository.Attach(phone);
}
}
请将isDeleted和是否新款不会持续到DB并以动态形式使用。 PhonesRepository Attach()是一样的。
我正在做这样的所有更新,因为我需要尽可能减少数据库调用次数。也许有这样的一个已知的最佳做法?
谢谢=)