2012-07-19 65 views
1

我正在使用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。你能指出我做錯了什麼嗎?

+0

http://stackoverflow.com/questions/5153573/error-on-using-transactionscope-in​​-ef4-sql-compact-4 – 2012-07-19 05:25:24

回答

3

推測,TransactionScope需要升級到分佈式或嵌套事務neither of which is supported by CE

這可能發生在例如因爲不止一個連接被同時打開 - TransactionScope and SQL Server Compact

CE不但是支持lightweight transactions,所以理論上只要你所有的連接都使用相同的連接字符串,並關閉打開另一個,TransactionScope不該」之前每個連接升級爲分佈式。

+0

謝謝,我不知道SQL CE有這樣的限制。 – 2012-07-19 05:32:28

+0

@Ashton Hearts - 恐怕我不使用CE很多 - 這裏有一些解決方法http://stackoverflow.com/questions/6690475/transactionscope-and-sql-server-compact – StuartLC 2012-07-19 05:43:07

+0

那麼,所有的連接做實際上使用相同的連接字符串。我還注意到,在調用'DatabaseController'內的方法時出現錯誤。否則,事務範圍工作正常。 – 2012-07-19 05:49:33