我使用了Dapper在asp.net MVC 4項目.NET F/W 4.6.1使用SQL Server 2016表現如何使用Dapper獲取存儲過程的返回值?
<packages>
<package id="Dapper" version="1.50.2" targetFramework="net461" />
</packages>
我有一個存儲過程從2個表中刪除這應該是事務
ALTER PROCEDURE [dbo].[FeedbackDelete] @FeedbackID UNIQUEIDENTIFIER
AS
SET NOCOUNT OFF
SET XACT_ABORT ON
BEGIN TRANSACTION
DELETE
FROM dbo.Document
WHERE FeedbackId = @FeedbackID
IF(@@ERROR != 0)
BEGIN
ROLLBACK TRANSACTION
RETURN 1
END
DELETE
FROM [dbo].[Feedback]
WHERE [FeedbackID] = @FeedbackID
IF(@@ERROR != 0 OR @@ROWCOUNT != 1)
BEGIN
ROLLBACK TRANSACTION
RETURN 1
END
COMMIT TRANSACTION
RETURN 0
我的回購方法使用這樣
public Response DeleteFeedback(Guid feedbackId)
{
string storedProcName = "FeedbackDelete";
int returnValue = int.MinValue;
using (var con = Connection)
{
con.Open();
returnValue = con.Execute(storedProcName, new { feedbackId }, commandType: CommandType.StoredProcedure);
}
return Convert.ToInt32(returnValue) == 0 ? new Response(Code.Success, "Feedback successfully deleted") : new Response(Code.Failure, "There was an error deleting feedback");
}
的的returnValue短小精悍我得到的是1,每次WH由於dapper返回受影響的行數,所以可以理解。
不過,我想我的存儲過程的return語句的價值交易過程中檢查錯誤刪除(這在我的情況下爲0表示成功,1對任何錯誤)
如何實現這個?
裸機ado.net我曾經做到這一點,它的工作
var returnValue = db.ExecuteScalar(storedProcName, new object[] { feedbackId });
憑藉短小精悍我試圖con.ExecuteScalar不工作,因爲短小精悍的元數據顯示,標//返回結果://的第一個單元格選擇
任何幫助將不勝感激?
這裏是我需要小巧玲瓏
執行ALTER PROCEDURE [dbo].[FeedbackUpdate]
@DocumentData VARBINARY(MAX),
@DocumentName NVARCHAR(100),
@FeedbackID UNIQUEIDENTIFIER,
@FirstName NVARCHAR(100),
@LastName NVARCHAR(100),
@Notes NVARCHAR(MAX)
AS
SET NOCOUNT ON
SET XACT_ABORT ON
BEGIN TRAN
UPDATE [dbo].[Feedback]
SET [FirstName] = @FirstName, [LastName] = @LastName, [Notes] = @Notes
WHERE [FeedbackID] = @FeedbackID
IF(@@ERROR != 0 OR @@ROWCOUNT != 1)
BEGIN
ROLLBACK TRAN
RETURN 1
END
IF DATALENGTH(@DocumentData) > 1
BEGIN
DELETE
FROM [dbo].[Document]
WHERE FeedbackId = @FeedbackId
IF(@@ERROR != 0)
BEGIN
ROLLBACK TRAN
RETURN 1
END
INSERT [dbo].[Document] (DocumentData,DocumentName,DocumentId,FeedbackId)
VALUES(@DocumentData,@DocumentName,NEWID(),@FeedbackID)
IF(@@ERROR != 0 OR @@ROWCOUNT != 1)
BEGIN
ROLLBACK TRAN
RETURN 1
END
END
COMMIT TRAN
RETURN 0
這是完全脫離主題,但會爲您節省一些主要的頭痛。大多數情況下,如果您定義本地變量,將其設置爲輸入參數,並在查詢中使用本地變量,則查詢速度會快得多,速度更快。通過做單件事情,我可以在大多數SPROC中輕鬆獲得10倍的性能。對不起,分心,但你會感謝我以後。 – SteveJ
https://stackoverflow.com/questions/14247081/return-values-from-dapper-net-query-with-stored-procedure – SteveJ
@SteveJ感謝您的有趣提示。任何有關爲什麼性能提高之前,我把我的團隊和更新存儲特效的解釋。我需要一個強大的合理理論來證明這個動盪;-) –