Note that there are some explanatory texts on larger screens.

plurals
  1. POBest practice for updating related entities in ASP.NET MVC + EF4 without loading entity first
    text
    copied!<p>I have seen some questions related to topic, but could not find answer for this scenario.</p> <p>I have structure like<br> <img src="https://i.stack.imgur.com/QyyqX.jpg" alt="alt text"></p> <p>Part of my controller</p> <pre><code>// // 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"); } </code></pre> <p>In my repository im doing something like this:</p> <pre><code>public void Update(Person person, ICollection&lt;Phone&gt; 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&lt;Phone&gt; phones) { if (phones == null || phones.Count == 0) return; foreach (var phone in phones.Where(o =&gt; o.IsDeleted &amp;&amp; !o.IsNew)) { PhoneRepository.Delete(phone); } foreach (var phone in phones.Where(o =&gt; !o.IsDeleted &amp;&amp; o.IsNew)) { party.Phones.Add(phone); } foreach (var phone in phones.Where(o =&gt; !o.IsDeleted &amp;&amp; !o.IsNew)) { phone.PartyID = party.ID; PhoneRepository.Attach(phone); } } </code></pre> <p>IsDeleted and IsNew are not persisted into db and used in dynamic form. PhonesRepository Attach() is same.</p> <p>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? </p> <p>Thanks=)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload