EF4如何在事务中包装2个更新

时间:2011-01-30 17:12:19

标签: .net entity-framework

我有两个独立的(没有关系)实体。这些的一些属性改变了,然后我调用SaveChanges。我需要将两个更新都包装到一个事务中,因为它们构成了我的应用程序状态。

执行两个更新,如SQL事件探查器中所示。但我看不到任何交易。 为什么EF4不围绕2次更新创建交易?我怎样才能做到这一点? (我已经尝试过transactioncope,但在Profiler中看不到任何交易)

任何想法?

2 个答案:

答案 0 :(得分:2)

这应该有效,但你需要按照正确的顺序做事。

这是一些sudo代码:

using (TransactionScope scope = new TransactionScope()) 
{ 
    //Do something with context1 
    //Do something with context2 

    //Save Changes but don't discard yet 
    context1.SaveChanges(false); 

    //Save Changes but don't discard yet 
    context2.SaveChanges(false); 

    //if we get here things are looking good. 
    scope.Complete(); 

    //If we get here it is save to accept all changes. 
    context1.AcceptAllChanges(); 
    context2.AcceptAllChanges(); 

} 

如果您在发布代码时仍有问题。

答案 1 :(得分:1)

嘿,即使我不写接受所有更改,我的记录也会保存

using (TransactionScope scope = new TransactionScope())
{
    Roll rsr = new Roll();
    rsr.RoleName = "krians";
    studentEntities.Rolls.AddObject(rsr);

    Roll rsssddr = new Roll();
    rsssddr.RoleName = "kriansss";
    studentEntities1.Rolls.AddObject(rsssddr);

    //Do something with context1 
    //Do something with context2 
    var sdfsf = studentEntities.ObjectStateManager;

    //Save Changes but don't discard yet 
    studentEntities.SaveChanges(false);

    var sdfssdfdsff = studentEntities.ObjectStateManager;
    var sdsdfdsffsf = studentEntities1.ObjectStateManager;

    //Save Changes but don't discard yet 
    studentEntities1.SaveChanges(false);

    var sdsdfdsffsasdfasdff = studentEntities1.ObjectStateManager;

    //if we get here things are looking good. 
    scope.Complete();

    var sdfsf3 = studentEntities.ObjectStateManager;
    var sdfsfasdfasdf3 = studentEntities1.ObjectStateManager;
    //If we get here it is save to accept all changes. 
    //studentEntities.AcceptAllChanges();
    //studentEntities1.AcceptAllChanges();
}