The connection object can not be enlisted in transaction scope

家住魔仙堡 提交于 2019-12-11 05:28:27

问题


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);
}

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: The underlying provider failed on Open. ---> System.InvalidOperationException: The connection object can not be enlisted in transaction scope.

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();
}        

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


回答1:


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

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

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.



来源:https://stackoverflow.com/questions/11554314/the-connection-object-can-not-be-enlisted-in-transaction-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!