I have seen some questions related to topic, but could not find answer for this scenario.
I have structure like
Part of my controller
//
// 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");
}
In my repository im doing something like this:
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 and IsNew are not persisted into db and used in dynamic form. PhonesRepository Attach() is same.
Im doing all of my updates like this because i need to reduce number of db calls as much as possible. Maybe there is a known best practice for this?
Thanks=)