2014-07-08 27 views
1

如果我使用作品的微軟實施單位從本教程: http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application工作單位 - 我不需要使用交易?

public class UnitOfWork : IDisposable 
{ 
    private SchoolContext context = new SchoolContext(); 
    private GenericRepository<Department> departmentRepository; 
    private GenericRepository<Course> courseRepository; 

    public GenericRepository<Department> DepartmentRepository 
    { 
     get 
     { 

      if (this.departmentRepository == null) 
      { 
       this.departmentRepository = new GenericRepository<Department>(context); 
      } 
      return departmentRepository; 
     } 
    } 

    public GenericRepository<Course> CourseRepository 
    { 
     get 
     { 

      if (this.courseRepository == null) 
      { 
       this.courseRepository = new GenericRepository<Course>(context); 
      } 
      return courseRepository; 
     } 
    } 

    public void Save() 
    { 
     context.SaveChanges(); 
    } 

    //...... 
} 

我並不需要使用事務時,我必須補充相關項目?例如,當我必須向數據庫添加訂單和訂單頭寸時,我不需要開始交易,因爲如果出現問題,則方法Save()將不會執行「是」?我對嗎?

_unitOfWork.OrdersRepository.Insert(order); 
_unitOfWork.OrderPositionsRepository.Insert(orderPosition); 
_unitOfWork.Save(); 

?? ??

回答

2

SaveChanges本身是事務性的。當您撥打Insert時,數據庫級別沒有任何反應,基於本教程僅在DbSet上調用Add。只有在調用SaveChanges時,數據庫纔會被觸發,並且發生在該點的所有事件都將在一個事務中發送。

+0

那麼是否有可能將訂單插入數據庫而無需訂單或不? – michael

+1

實體框架負責這個。它知道它需要保存相關的類,然後才能將具有外鍵的類保存到該類中。 –

1

如果在一個方法中有多個保存更改,或者使用相同上下文的方法調用鏈,則需要事務。

然後,您可以在最終更新失敗時回滾多個保存更改。

一個例子是在工作單元(IE泛型類)下的一個實體封裝實體的多個存儲庫。您可能會在每個存儲庫中插入和保存許多函數。但最後你可能會發現一個問題,導致你回退以前的保存。

EG需要擊中許多存儲庫並執行復雜操作的服務層。

+0

thx您非常瞭解 - 當我必須使用交易時,我明白了 – michael