连接对象不能在事务范围中登记

时间:2012-07-19 05:13:34

标签: c# entity-framework sql-server-ce transactionscope

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

// 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方法时,我收到以下错误:

System.Data.EntityException: The underlying provider failed on Open. ---> System.InvalidOperationException: The connection object can not be enlisted in transaction scope.

DatabaseController具有以下代码:

// 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。你能指出我做错了什么吗?

1 个答案:

答案 0 :(得分:3)

据猜测,TransactionScope需要升级到分布式或嵌套式事务neither of which is supported by CE

可能会发生这种情况,例如因为同时打开了多个连接 - TransactionScope and SQL Server Compact

但是,CE确实支持lightweight transactions,因此理论上只要所有连接都使用相同的连接字符串,并且在打开另一个连接之前关闭每个连接,TransactionScope就不应该升级为分布式连接。