我的問題是相似的,我搜查這裏。試圖編寫一個單元測試來測試我的服務,我得到了同樣的「事務不與命令的連接關聯」異常。我的情況不同之處在於,我正在使用的唯一事務(在我測試的服務中)正確地處理了它的連接,所以我不認爲這適用。
(我使用的ServiceStack v3.9.71)
我的測試代碼(失敗)是這樣的:
[Test]
public void Test_Service_Delete() {
var DatabaseFactory = new OrmLiteConnectionFactory(":memory:", false, SqliteDialect.Provider, true);
using (var db = DatabaseFactory.OpenDbConnection()) {
var parentId = db.InsertParam(new ParentObject { name = "Bob" }, true);
db.Insert(new ChildObject { ParentId = parentId, name = "Sam" });
var service = Container.Resolve<TestService>();
var response = service.Delete(new DeleteRequestObject(parentId));
Assert.That(db.Select<ParentObject>(parentId), Has.Count.EqualTo(0));
Assert.That(db.Select<ChildObject>("ParentId = {0}", parentId), Has.Count.EqualTo(0));
}
}
我TestService.Delete方法曾在它的事務(因爲它會刪除對象和任何相關的子對象),但它被包裹在一個使用塊,像這樣:
using (var db = DatabaseFactory.OpenDbConnection()) {
using (var transaction = db.BeginTransaction(IsolationLevel.ReadCommitted)) {
// do stuff here
}
}
不過,除了W「交易不與命令的連接相關聯」在調用service.Delete之後在第一行中拋出。
我首先要解決它(沒有工作)的嘗試是這樣的:
[Test]
public void Test_Service_Delete() {
var DatabaseFactory = new OrmLiteConnectionFactory(":memory:", false, SqliteDialect.Provider, true);
int parentId;
using (var db = DatabaseFactory.OpenDbConnection()) {
parentId = db.InsertParam(new ParentObject { name = "Bob" }, true);
db.Insert(new ChildObject { ParentId = parentId, name = "Sam" });
}
var service = Container.Resolve<TestService>();
var response = service.Delete(new DeleteRequestObject(parentId));
using (var db = DatabaseFactory.OpenDbConnection()) {
Assert.That(db.Select<ParentObject>(parentId), Has.Count.EqualTo(0));
Assert.That(db.Select<ChildObject>("ParentId = {0}", parentId), Has.Count.EqualTo(0));
}
}
什麼工作最終被包裹在一個事務服務呼叫後調用數據庫。
[Test]
public void Test_Service_Delete() {
var DatabaseFactory = new OrmLiteConnectionFactory(":memory:", false, SqliteDialect.Provider, true);
int parentId;
using (var db = DatabaseFactory.OpenDbConnection()) {
parentId = db.InsertParam(new ParentObject { name = "Bob" }, true);
db.Insert(new ChildObject { ParentId = parentId, name = "Sam" });
}
var service = Container.Resolve<TestService>();
var response = service.Delete(new DeleteRequestObject(parentId));
using (var db = DatabaseFactory.OpenDbConnection()) {
using (var transaction = db.OpenTransaction()) {
Assert.That(db.Select<ParentObject>(parentId), Has.Count.EqualTo(0));
Assert.That(db.Select<ChildObject>("ParentId = {0}", parentId), Has.Count.EqualTo(0));
}
}
}
我仍然模糊爲什麼這種解決方法工作,但我想我會記錄它的任何人跑到這。