调用Context.Database.SqlQuery时获取从存储过程的整数结果使用实体框架失败
我试图从实体框架通过以下方式调用存储过程:调用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你可以看到存储过程的工作
从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必须是唯一的数据库参数或值。 这可能是这里的问题?
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;
所以返回值回来的一个结果。
实际上,存储过程没有声明输出参数,所以我不能使用这样的[dbo]。[usp_InsertInspectionEventPublic] OUT myOutputParameter ...链接板在调用存储过程时以这种方式生成sql。在存储过程中,有一行会与您建议的内容相同,将值赋给id后返回id。对不起,没有在评论中的变量“at”,似乎这个输入不允许它 – Heinrich
它不是一个存储过程输出参数,它是一个返回值。这就是为什么它是'exec @RETURN_VALUE = procname ...'而不是'exec procname @RETURN_VALUE。 。 。'return @ id'输出数据作为返回值'select @id id'返回结果集,如SqlQuery
我很困惑,你的意思是 select id = SCOPE_IDENTITY()from TEMPTABLE 返回ID 返回结果集? – Heinrich
返回值与结果集不同。 SqlQuery返回结果集。我不是那么熟悉,但是你可能能够从'params'(这是一个关键字,所以不使用它)访问参数'ReturnValue' – Crowcoder