从业务逻辑层将事务与实体框架一起使用
本文关键字:框架 实体 一起 事务 业务 | 更新日期: 2023-09-27 18:33:24
请先看看这个:良好的编码实践
所以,这是我的设计。
- 网站2.业务逻辑层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();
}
}
}
是的
,在同一线程中,EF 将正确考虑事务范围(如果存在)。如果 EF 已在其中,则不会创建新事务。
但是,您必须小心,因为如果您在没有事务的情况下查询数据库,那么您将获得脏读。因为如果事务不存在,EF 将不会读取事务中的任何内容,但如果它不存在,则在保存更改时会创建新事务。
在您的代码中,您只保存事务中的更改,但在阅读时应该小心,并且应该将查询也封装在较小的单元中。