2012-05-08 38 views
0

請看到這第一: Good Coding Practices用的EntityFramework使用事務從商業邏輯層

所以,這是我設計的。

  1. 網站 2.Business邏輯層 3.DALFacade(我們使用dalfacade隱藏數據訪問,因爲我們使用2家不同的商店,SQL和DB2) 4.DAL

在DAL我們使用工作單元模式和存儲庫模式。 1.這裏最大的問題是:如果下面的代碼對於從業務邏輯創建的事務運行正常。

Page: 

public partial class NewBonusRequest : System.Web.UI.Page 
{ 

    #region Constructor and Instantiation of Business Logic 
     /// <summary> 
     /// Property that holds the Business Logic type to call methods 
     /// </summary> 
     public IRequestBL RequestBL { get; private set; } 

     /// <summary> 
     /// The default constructor will use the default implementation of the business logic interface 
     /// </summary> 
     public Request() 
      : this(new RequestBL()) 
     { 
     } 

     /// <summary> 
     /// The constructor accepts a IEcoBonusRequestFacade type 
     /// </summary> 
     /// <param name="ecoBonusRequestBL">IEcoBonusRequestFacade type</param> 
     public NewRequest(IRequestBL RequestBL) 
     { 
      RequestBL = RequestBL; 
     } 
    #endregion 


    protected void PageLoad(object sender, EventArgs e) 
    { 
     if(!Page.IsPostBack) 
     { 

     } 
    } 


    #region Control Events 
     protected void BtnSubmitRequestClick(object sender, EventArgs e) 
     { 
      var request= new Request 
             { 
              IsOnHold = true 
              //All other properties go here. 
             }; 

      RequestBL.Save(request); 
     } 



    Business Logic Code. 

    public interface IRequestBL 
    { 
     void Save(Request request); 
    } 

    /// <summary> 
    /// Class in charge of the business logic for EcoBonusRequest 
    /// </summary> 
    public class RequestBL : IRequestBL 
    { 
     /// <summary> 


     /// <summary> 
     /// Saves a new ecobonus request into database and evaluate business rules here 
     /// </summary> 
     /// <param name="ecoBonusWorkflow">EcoBonusWorkflow entity</param> 
     public void Save(Request Request) 
     { 
      using (var scope = new TransactionScope()) 
      { 
       Request.Save(request); 
       // Call to other DALCFacade methods that insert data in different tables 
       // OtherObject.Save(otherobject) 
       scope.Complete(); 
      } 
     } 
    } 

回答

1

是的,在同一個線程中,如果EF存在,EF將正確地考慮事務範圍。如果EF已經在一箇中,EF不會創建新的交易。

但是,你必須要小心,因爲如果你沒有事務查詢數據庫,那麼你會得到髒讀。因爲如果EF不存在,EF就不會讀取任何事務,但如果它在保存更改時不存在,它將創建新的事務。

在你的代碼只節省了交易的變化,但在閱讀你要小心,你應該也概括了您的查詢範圍更小的單元。