Note that there are some explanatory texts on larger screens.

plurals
  1. PORepository.Update strategy using EF4 Code First?
    primarykey
    data
    text
    <p>I'm working on an MVC site with Entity Framework Code First, using Ninject for DI to the controllers, and I've run into a design question. I've seen two methods used for updates with Code First. The first uses a "get by id," changes the values of the object returned, then calls <code>Context.SaveChanges()</code>, like this:</p> <p>Controller:</p> <pre><code>[HttpPost] public ActionResult Edit(int id, FormCollection collection) { //Create a vm to hold the data from the form. var sectionVm = new SectionEditViewModel(); //Copy the data from the http header to the object. UpdateModel(sectionVm); //Get the object from the database. //_sectionRepository is injected in to the constructor. var section = _sectionRepository.GetById(sectionVm.SectionId); //Map from the view model to the actual model. var viewSection = Mapper.Map(sectionVm, section); _sectionRepository.Update(); return RedirectToAction("Index"); } </code></pre> <p>Repository:</p> <pre><code> public void Update() { _context.SaveChanges(); } </code></pre> <p>The second method creates the model object, attaches it to the context, changes the state of the object, then calls <code>SaveChanges()</code>. Illustrated here with a test method as the consumer: Test:</p> <pre><code> [TestMethod] public void CanUpdateSection() { var repo = new SectionRepository(); var testSection = GetMockSection(); testSection.SomeProperty = "A new value"; testContact.AnotherProperty = "Another new value"; repo.Update(testSection); var persistedUpdatedSection = repo.GetById(testSection.Id); Assert.IsNotNull(persistedUpdatedSection); CompareSections(testSection, persistedUpdatedSection); } </code></pre> <p>Repository:</p> <pre><code> public void Update(Section entity) { using(var context = new SectionContext()) { context.Sections.Attach(entity); context.Entry(entity).State = System.Data.EntityState.Modified; context.SaveChanges(); } } </code></pre> <p>Which way is preferable, or is there another, better way?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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