2011-07-31 77 views
7

我想提交一個事務到我的Sql Server 2008數據庫 - 首先是2個插入的後面是幾個更新,但是,只要它試圖執行第一個更新,我就會得到以下錯誤:Dapper.net交易問題

ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized.

下面的代碼,爲了簡潔而稍加編輯:

using (_cn) 
{ 
    _cn.Open(); 
    IDbTransaction transaction = _cn.BeginTransaction(); 
    topicId = (int)_cn.Query<decimal>(qAddTopic, new { pForumId = topic.ForumId }, transaction).Single(); 
    postId = (int)_cn.Query<decimal>(qAddPost, new { pTopicId = topicId }, transaction).Single(); 

    _cn.Execute(qUpdateForums, new { pLastPostId = postId }); 
    _cn.Execute((qUpdateSiteTotals)); 

    transaction.Commit(); 
} 

第2個插入做工精細,但只要它會嘗試進行更新的一個,沒有喜悅。

回答

11

我已經找到了問題 - 我只是錯過了交易PARAM當我打電話的更新,而與被做工精細以前插入,我已經包括了IDbTransaction PARAM!我的錯!

實施例:

Connection.Query<Entitiy>("sqlQuery",param: new { id= ID}, transaction: Transaction) 
+1

'Connection.Query (「sqlQuery」,param:new { id = ID},transaction:Transaction)' – vaheeds

5

如果可能,Microsoft建議使用TransactionScope over數據庫IDbTransaction。下面的代碼應該可以工作,假設你的SQL沒有問題,並且託管提供程序會自動登錄環境事務 - 這是行爲良好的提供程序需要執行的操作。

using (var ts = new TransactionScope()) 
{ 
    using (_cn) 
    { 
    _cn.Open(); 
    ... 
    } 

    ts.complete(); 
} 
+1

感謝您的答覆,奧利弗。不幸的是,它看起來像Dapper.net不支持TransactionScope,只是IDbTransaction :( – marcusstarnes

+0

@marcusstarnes你確定嗎?它應該工作。只是不使用BeginTransaction和提交。transactionScope將處理其餘 – adt

+2

Dapper是絕對不可知的交易。 m使用TransactionScope和Dapper一起完全沒有問題 –