Entity framework UnitofWork[aspnetboilerplate]事务管理
我目前正在实施aspnetboilerplate的事务管理 下面是我用来插入订单和与订单关联的产品的方法Entity framework UnitofWork[aspnetboilerplate]事务管理,entity-framework,transactions,entity-framework-6,aspnetboilerplate,Entity Framework,Transactions,Entity Framework 6,Aspnetboilerplate,我目前正在实施aspnetboilerplate的事务管理 下面是我用来插入订单和与订单关联的产品的方法 public class OrderController { IOrderAppService _orderAppService; public OrderController(IOrderAppService orderAppService) { _orderAppService = orderAppService;
public class OrderController
{
IOrderAppService _orderAppService;
public OrderController(IOrderAppService orderAppService)
{
_orderAppService = orderAppService;
}
public void TestOrder()
{
_orderAppService.TestTransaction();
}
}
public class OrderAppService : IOrderAppService
{
//repositories are injected here
public void TestTransaction()
{
//Created 'order' and 'products' here
//Committing the created objects
CommitOrderTransaction();
}
private void CommitOrderTransaction()
{
using (var unitOfWork = _unitOfWorkManager.Begin())
{
//Inserts the Order record
CommitInsertOrderHeader(); // Order Header is saved in database by using SaveChanges() method
//Inserts the Product records associated with OrderId
CommitInsertOrderDetails();
unitOfWork.Complete();
}
}
}
正如aspnetboilerplate文档所述,
如果当前工作单元是事务性的,则如果发生异常,事务中的所有更改都将回滚,即使是已保存的更改
在我的例子中,当插入OrderDetails时发生异常时,我希望头记录也回滚,但数据库中仍然有订单头记录。如果您两次调用SaveChanges(),并且没有跨这两个调用使用TransactionScope,那么您将无法回滚第一次调用。我不知道UnitOfWork在这里做什么,但是如果您正在使用的DbContext没有在UoW中使用,那么就不会发生任何事情。DbContext在技术上已经是它自己的工作单元了。您应该将订单和订单详细信息添加到同一DbContext中,并只调用一次SaveChanges()。然后,您就可以在该场景中回滚这两个事务。您不需要手动处理事务。ABP为你处理!所有应用程序服务方法都自动设置为UnitOfWork。这是一个原子操作。因此,如果在事务的中间出现任何异常,则所有的DB操作都会被回滚。
更多信息签出显示
committensertorderheader
@aron\u orderHeaderRepository.Insert(orderHeader)的实现;CurrentUnitOfWork.SaveChanges();committerdTransaction
是否包装在try
-catch
中?否,该方法没有try catch调用方是否有try
-catch
?如果需要使用SaveChanges()怎么办首先在“OrderHeader”中获取“OrderId”并将其用于在“OrderDetails”表中插入记录?如果您正确连接了FKs,EF应该为您解决这一问题。当您同时保存为new并且订单详细信息直接引用header类时,EF将知道如何处理这个问题。