2010-12-14 11 views
1

私はEntity Framework Code FirstでMVCサイトに取り組んでいます。コントローラにDI用にNinjectを使用しています。私は設計に関する質問をしました。コードファーストでの更新には2つの方法があります。最初は "IDによって取得" を使用し返されたオブジェクトの値を変更し、このように、Context.SaveChanges()を呼び出し:EF4コードを使用したRepository.Update戦略まずは?

コントローラー:

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

レポジトリ:

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

第二の方法モデルオブジェクトを作成し、コンテキストにアタッチし、オブジェクトの状態を変更してから、SaveChanges()を呼び出します。消費者としての試験方法とここに示さ: テスト:

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

レポジトリ:好ましい、または別の、より良い方法がある

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

方法?

答えて

1

最初の方法が優れています。独自のリポジトリメソッドにSaveChanges()メソッドを保持している場合は、多くの編集を行い、Update()を使用してそれらを一度にコミットしようとすることができます。 1つの編集に問題がある場合、Update()が呼び出されるとすべての変更がロールバックされます。

関連する問題