如何在Entity Framework Core中实现环境事务? [英] How to implement ambient transaction in Entity Framework Core?
问题描述
我需要在两个模型(使用两个分开的有界上下文)下实现交易。像这样的代码:
I need to realize transaction under two models (using two separated bounded contexts). So code like this:
using (TransactionScope scope = new TransactionScope())
{
//Operation 1
using(var context1 = new Context1())
{
context1.Add(someCollection1);
context1.SaveChanges();
}
//Operation 2
using(var context2 = new Context2())
{
context2.Add(someCollection2);
context2.SaveChanges();
}
scope.Complete();
}
返回例外:
已检测到环境事务。实体框架核心不支持
不支持环境交易。请参阅
http://go.microsoft.com/fwlink/?LinkId=800142
在Link中,他们建议对两个上下文使用一个连接。并在使用context1的块中使用context2。
In Link they advice to use one connection for two context. And use context2 in using block of context1.
但是如果我为每种模型使用自己的控制器/服务:
But if I use own controller/service for every model:
using (TransactionScope scope = new TransactionScope())
{
service1.DoWork();
service2.DoWork();
scope.Complete();
}
我应该如何实现?在方法中添加连接作为参数-似乎很荒谬。带有连接的初始化服务也是个坏主意。
How should I implement this? Add connection as parameter in method - seems absurdly. Init service with connection also bad idea.
推荐答案
在代码片段下使用
using (var context = new MyContext())
{
using (var transaction = context.Database.BeginTransaction())
{
try
{
var customer = context.Customers
.Where(c => c.CustomerId == 2)
.FirstOrDefault();
customer.Address = "43 rue St. Laurent";
context.SaveChanges();
var newCustomer = new Customer
{
FirstName = "Elizabeth",
LastName = "Lincoln",
Address = "23 Tsawassen Blvd."
};
context.Customers.Add(newCustomer);
context.SaveChanges();
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
}
}
}
更多详细信息: https://entityframeworkcore.com/saving-data-transaction
这篇关于如何在Entity Framework Core中实现环境事务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!