当你有这样的代码:
Something something = new Something();
BlahEntities b = new BlahEntities()
b.AddToSomethingSet(something);
b.SaveChanges();
如何在事务内运行此加法?
当你有这样的代码:
Something something = new Something();
BlahEntities b = new BlahEntities()
b.AddToSomethingSet(something);
b.SaveChanges();
如何在事务内运行此加法?
ObjectContext有一个连接属性,您可以使用它来管理事务。
using (var context = new BlahEntities())
using (var tx = context.BeginTransaction())
{
// do db stuff here...
tx.Commit();
}
如果出现异常,则事务将被回滚。由于调用BeginTransaction()需要打开连接,因此在扩展方法中包装调用BeginTransaction()是有意义的。
public static DbTransaction BeginTransaction(this ObjectContext context)
{
if (context.Connection.State != ConnectionState.Open)
{
context.Connection.Open();
}
return context.Connection.BeginTransaction();
}
我认为这种方法比TransactionScope更有用的情况是,当你需要访问两个数据源并且只需要对其中一个连接进行事务控制时。在这种情况下,TransactionScope会升级为分布式事务,而这可能是不必要的。
你可以将代码放在事务范围内
using(TransactionScope scope = new TransactionScope())
{
// Your code
scope.Complete(); // To commit.
}
TransactionScope 位于 System.Transactions 命名空间中,该命名空间位于同名程序集中(您可能需要手动将其添加到项目中)。
using System.Transactions;
using (TransactionScope scope = new TransactionScope())
{
try
{
using(DataContext contextObject = new DataContext(ConnectionString))
{
contextObject.Connection.Open();
// First SaveChange method.
contextObject.SaveChanges();
// Second SaveChange method.
contextObject.SaveChanges();
//--continue to nth save changes
// If all execution successful
scope.Complete();
}
}
catch(Exception ex)
{
// If any exception is caught, roll back the entire transaction and end the scope.
scope.Dispose();
}
finally
{
// Close the opened connection
if (contextObject.Connection.State == ConnectionState.Open)
{
contextObject.Connection.Close();
}
}
}
请点击下面的链接查看详细解释:https://msdn.microsoft.com/zh-cn/data/dn456843.aspx
了解更多信息:EntityFramework和Transaction
context.Connection.BeginTransaction
。 - Mike Chamberlain