0

请先看看这个: 良好的编码实践

所以,这是我的设计。

  1. Website 2.Business Logic Layer 3.DALFacade (我们使用dalfacade来隐藏数据访问,因为我们使用了2个不同的store,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();
            }
        }
    }
4

1 回答 1

1

是的,在同一个线程中,EF 将正确考虑事务范围(如果存在)。如果已经在一个事务中,EF 将不会创建新事务。

但是,您必须小心,因为如果您在没有事务的情况下查询数据库,那么您将获得脏读。因为如果事务不存在,EF 将不会读取事务中的任何内容,但如果在保存更改时不存在,它将创建新事务。

在您的代码中,您只是保存事务中的更改,但在阅读时应该小心,并且您也应该将查询封装在更小的单元中。

于 2012-05-08T08:15:24.857 回答