2017-09-14 117 views
1

我試圖從實體框架通過以下方式調用存儲過程:調用Context.Database.SqlQuery時獲取從存儲過程的整數結果使用實體框架失敗<int>

Context.Database.SqlQuery<int>(sqlSP, params).FirstOrDefault(); 

,但我得到這個錯誤:

The data reader has more than one field. Multiple fields are not valid for EDM primitive or enumeration types

隨着LinqPad你可以看到存儲過程的工作

enter image description here

從LinqPad生成的代碼在SQL一樣調用如下

-- Region Parameters 
DECLARE @RETURN_VALUE Int 
DECLARE @contenttype VarChar(50) = '' 
DECLARE @image VarBinary(1000) = null 
DECLARE @applicationid Int = 81725 
DECLARE @statusid Int = 10 
DECLARE @notes VarChar(1000) = '' 
DECLARE @requestuserid Int = 59 
DECLARE @assigneduserid Int = 655 
DECLARE @parentid Int = 0 
DECLARE @eventid Int = 0 
DECLARE @discipline Int = 5 
DECLARE @replyby DateTime = '2017-09-14 16:22:40.082' 
DECLARE @workitemid Int = 81725 
DECLARE @messagetype Int = 2 
DECLARE @inspectionid Int = 6081 
DECLARE @floor SmallInt = 3 
-- EndRegion 
exec @RETURN_VALUE = [dbo].[usp_InsertInspectionEventPublic] @contenttype, @image, @applicationid, @statusid, @notes, @requestuserid, @assigneduserid, @parentid, @eventid, @discipline, @replyby, @workitemid, @messagetype, @inspectionid, @floor 

存儲過程始終以下列方式返回ID:

select @id = SCOPE_IDENTITY() from TEMPTABLE 
Return @id 

我想這太:

var returnCode = new SqlParameter("@ReturnCode", SqlDbType.Int); 
returnCode.Direction = ParameterDirection.ReturnValue; 

var sql = "exec @ReturnCode =dbo.usp_insertinspectioneventpublic @contenttype, @image, @applicationid, @statusid, @notes, @requestuserid, @assigneduserid, @parentid, @eventid, @discipline, @replyby, @workitemid, @messagetype, @inspectionid, @floor"; 
var data = Context.Database.SqlQuery<int>(sql, returnCode, inParameters); 
var res = data.FirstOrDefault(); 
return res; 

但我得到了另一個錯誤的方法:當執行一個命令,paramerte rs必須是唯一的數據庫參數或值。 這可能是這裏的問題?

+0

返回值與結果集不同。 SqlQuery返回結果集。我不是那麼熟悉,但是你可能能夠從'params'(這是一個關鍵字,所以不使用它)訪問參數'ReturnValue' – Crowcoder

回答

0

SqlQuery<T>()正在查找結果集,而不是輸出參數。

無論是地圖的輸出參數和運行批處理與ExecuteSqlCommand(SQL,則params),或寫SQLSP一批這樣的:

declare @RETURN_VALUE INT; 
exec @RETURN_VALUE = [dbo].[usp_InsertInspectionEventPublic] @contenttype, @image, @applicationid, @statusid, @notes, @requestuserid, @assigneduserid, @parentid, @eventid, @discipline, @replyby, @workitemid, @messagetype, @inspectionid, @floor; 
SELECT @RETURN_VALUE RETURN_VALUE; 

所以返回值回來的一個結果。

+0

實際上,存儲過程沒有聲明輸出參數,所以我不能使用這樣的[dbo]。[usp_InsertInspectionEventPublic] OUT myOutputParameter ...鏈接板在調用存儲過程時以這種方式生成sql。在存儲過程中,有一行會與您建議的內容相同,將值賦給id後返回id。對不起,沒有在評論中的變量「at」,似乎這個輸入不允許它 – Heinrich

+0

它不是一個存儲過程輸出參數,它是一個返回值。這就是爲什麼它是'exec @RETURN_VALUE = procname ...'而不是'exec procname @RETURN_VALUE。 。 。'return @ id'輸出數據作爲返回值'select @id id'返回結果集,如SqlQuery 所期望的那樣。 –

+0

我很困惑,你的意思是 select id = SCOPE_IDENTITY()from TEMPTABLE 返回ID 返回結果集? – Heinrich

相關問題