use*_*534 17 c# linq datacontext transactions linq-to-sql
我可以使用带有datacontext的事务,以便在出错后可以回滚上下文的状态吗?如果是这样,那怎么办?
lep*_*pie 18
我一直在测试中使用它们:)
try
{
dc.Connection.Open();
dc.Transaction = dc.Connection.BeginTransaction();
dc.SubmitChanges();
}
finally
{
dc.Transaction.Rollback();
}
Run Code Online (Sandbox Code Playgroud)
UPDATE
这将始终在事后回滚.我在测试中使用它.
Ric*_*ard 15
默认情况下,DataContext将选择环境事务,因此只需确保范围内存在事务.细节成为主要问题:
这简化了一些原型代码,真正的代码使用帮助程序来创建具有策略驱动选项的事务(原型的目的之一是检查这些选项的影响).
using (var trans = new TransactionScope(
TransactionScopeOption.Required,
new TransactionOptions {
IsolationLevel = IsolationLevel.ReadCommitted
},
EnterpriseServicesInteropOption.Automatic)) {
// Perform operations using your DC, including submitting changes
if (allOK) {
trans.Complete();
}
}
Run Code Online (Sandbox Code Playgroud)
如果未调用Complete(),则将回滚事务.如果存在包含事务范围,则内部事务和外部事务都需要完成以便对要提交的数据库进行更改.
Dam*_*ien 12
它不像TransactionScope方法那么简单,但据我所知,这是为LINQ-to-SQL执行此操作的"正确"方法.它不需要任何对System.Transactions的引用.
dataContext.Connection.Open();
using (dataContext.Transaction = dataContext.Connection.BeginTransaction())
{
dataContext.SubmitChanges();
if (allOK)
{
dataContext.Transaction.Commit();
}
else
{
dataContext.Transaction.RollBack();
}
}
Run Code Online (Sandbox Code Playgroud)
当然,只有在打算在使用中进行进一步的数据操作时才需要RollBack,否则将自动丢弃更改.
Phi*_*ppe 10
这样的事情,可能是:
try
{
using (TransactionScope scope = new TransactionScope())
{
//Do some stuff
//Submit changes, use ConflictMode to specify what to do
context.SubmitChanges(ConflictMode.ContinueOnConflict);
scope.Complete();
}
}
catch (ChangeConflictException cce)
{
//Exception, as the scope was not completed it will rollback
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38476 次 |
| 最近记录: |