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