连接对象无法登录在事务范围内 [英] The connection object can not be enlisted in transaction scope

查看:173
本文介绍了连接对象无法登录在事务范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用TransactionScope来测试数据库操作。这是测试类:

I am using TransactionScope to test database actions. This is the test class:

// Test class

private TransactionScope _transactionScope = null;

[TestInitialize]
public void Initialize()
{
    _transactionScope = new TransactionScope();
}

[TestCleanup]
public void Cleanup()
{
    if (_transactionScope != null)
    {
        _transactionScope.Dispose();
        _transactionScope = null;
    }
}

[TestMethod]
[DeploymentItem("Db.sdf")]
public void AddToPresentationsTest()
{           
    var item = TestItem();
    var db = new DbEntities();
    var target = new DatabaseController {Entities = db};
    target.AddToItems(item);
    var result = db.Items.Any(p => p.Text.Equals(item.Text));
    Assert.IsTrue(result);
}

TransactionScope是在每次测试之前创建的,并在测试完成后进行处理。当调用AddToItems方法时,我得到以下错误:

A TransactionScope is created before each test and is disposed after the test is complete. When AddToItems method is called I get the following error:

System.Data.EntityException:底层提供程序在Open上失败。 ---> System.InvalidOperationException:连接对象不能被登记在事务范围内。

DatabaseController具有以下代码:

DatabaseController has the following code:

// DatabaseController class

private DbEntities _entities;

public DbEntities Entities
{
    get { return _entities ?? (_entities = new DbEntities());}
    set { _entities = value; }
}

protected override void Dispose(bool disposing)
{
    if (disposing && _entities != null)
    {
        _entities.Dispose();
    }
    base.Dispose(disposing);
}

public void AddToItems(Item item)
{
    Entities.Items.Add(item);
    Entities.SaveChanges();
}        

我使用Sql Server Compact 4.0。你能指出我做错了什么吗?

I use Sql Server Compact 4.0. Could you please point out what am I doing wrong?

推荐答案

事实上,TransactionScope需要升级到分布式或嵌套事务, CE都不支持这些

At a guess, TransactionScope needs to escalate to a distributed or nested transaction, neither of which is supported by CE.

这可能发生,例如因为同时打开多个连接 -
TransactionScope和SQL Server Compact

This may be happening e.g. because more than one connection is being opened concurrently - TransactionScope and SQL Server Compact

但是,CE支持轻量级事务,所以理论上只要所有的连接都使用相同的连接字符串,并且在打开另一个连接之前关闭每个连接, TransactionScope 不应该升级到分发。

CE does however support lightweight transactions, so in theory as long as all your connections use the same connection string, and that you close each connection before opening another, TransactionScope shouldn't escalate to distributed.

这篇关于连接对象无法登录在事务范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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