EF:如何在事务中两次调用 SaveChanges? [英] EF: How do I call SaveChanges twice inside a transaction?

查看:31
本文介绍了EF:如何在事务中两次调用 SaveChanges?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用实体框架(在我的例子中是代码优先),我有一个操作需要我调用 SaveChanges 来更新数据库中的一个对象,然后再次调用 SaveChanges 来更新另一个对象.(我需要第一个 SaveChanges 来解决 EF 无法确定首先更新哪个对象的问题).

Using Entity Framework (code first in my case), I have an operation that requires me to call SaveChanges to update one object in the DB, and then SaveChanges again to update another object. (I need the first SaveChanges to resolve an issue where EF can't figure out which object to update first).

我尝试过:

using (var transaction = new TransactionScope())
{
    // Do something

    db.SaveChanges();

    // Do something else

    db.SaveChanges();

    tramsaction.Complete();
}

当我运行它时,我在第二个 SaveChanges 调用中得到一个异常,说底层提供程序在打开时失败".内部异常表示我的机器上未启用 MSDTC.

When I run that, I get an exception at the second SaveChanges call, saying "the underlying provider failed on open". The inner exception says that MSDTC is not enabled on my machine.

现在,我在其他地方看到过一些帖子,描述了如何启用 MSDTC,但似乎我还需要启用网络访问等.这在这里听起来完全是矫枉过正,因为没有涉及其他数据库,更不用说其他服务器.我不想做一些会降低我的整个应用程序的安全性(或更慢)的事情.

Now, I've seen posts elsewhere that describe how to enable MSDTC, but it seems that I would also need to enable network access, etc. This sounds like complete overkill here, since there are no other databases involved, let alone other servers. I don't want to do something that's going to make my whole application less secure (or slower).

当然必须有更轻量级的方法来做到这一点(最好没有 MSDTC)?!

Surely there must be a more lightweight way of doing this (ideally without MSDTC)?!

推荐答案

这可能是由您的事务中使用的两个不同连接引起的.尝试手动控制您的操作的连接:

It is probably caused by two different connections used in your transaction. Try to control connection for your operation manually:

var objectContext = ((IObjectContextAdapter)db).ObjectContext;

try {
    //Open Connection
    objectContext.Connection.Open();

    using (var transaction = new TransactionScope()) {
        // Do something

        db.SaveChanges();

        // Do something else

        db.SaveChanges();

        transaction.Complete();
    }
} finally {
    //Close connection after commit
    objectContext.Connection.Close();
} 

这篇关于EF:如何在事务中两次调用 SaveChanges?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆