2010-12-14 54 views
1

Je travaille sur un site MVC avec Entity Framework Code Premièrement, en utilisant Ninject pour DI sur les contrôleurs, et j'ai rencontré une question de conception. J'ai vu deux méthodes utilisées pour les mises à jour avec Code First. La première utilise un "get par id," modifie les valeurs de l'objet retourné, puis appelle Context.SaveChanges(), comme ceci:Repository.Update stratégie en utilisant le code EF4 d'abord?

Controller:

[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"); 
} 

Repository:

public void Update() 
    { 
     _context.SaveChanges(); 
    } 

La deuxième méthode crée l'objet modèle, l'attache au contexte, modifie l'état de l'objet, puis appelle SaveChanges(). Illustré ici avec une méthode d'essai comme le consommateur: Test:

[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); 
    } 

Repository:

public void Update(Section entity) 
    { 
     using(var context = new SectionContext()) 
     { 
      context.Sections.Attach(entity); 
      context.Entry(entity).State = System.Data.EntityState.Modified; 
      context.SaveChanges(); 
     } 
    } 

Quelle manière est préférable, ou est-il une autre, une meilleure façon?

Répondre

1

La première façon est meilleure. Si vous conservez la méthode SaveChanges() dans sa propre méthode Repository, vous pouvez effectuer de nombreuses modifications, puis tenter de les valider toutes en même temps à l'aide de Update(). S'il y a un problème avec une modification, toutes vos modifications seront annulées lors de l'appel de Update().