entity framework和SCOPE_IDENTITY
我有一个插入表中的存储过程然后执行此行
SET @returnVal = SCOPE_IDENTITY();
之后我尝试了两个:
SELECT @returnVal
和
return @returnVal
当我从Microsoft SQL Server Management Studio执行存储过程时,我使用SELECT @returnVal
获得预期结果 – SELECT @returnVal
插入数据的标识列。
但是,当我将存储过程添加到我的ADO.Net实体数据模型/ EntityFramework类/ .edmx类并在我的C#代码中执行存储过程时,我得到的值-1返回但是没有失败。
是否有可能获得我想要的值,新的身份值,返回?
我意识到我可以手动将存储过程绑定到我的模型中表的插入操作 – 但这不是一个选项。 每次重新生成模型类时,都需要执行此手动工作的插入过程太多。
在过程定义中声明参数的输出类型:
create procedure [dbo].[Procedurename] @returnVal int output as SET @returnVal = SCOPE_IDENTITY();
并在调用存储过程时将其称为:
declare @returnVal int exec Procedurename @returnVal output print @returnVal
取自OP的问题
添加输出参数(答案标记如下)。
存储过程签名现在看起来像这样:
我的存储过程签名现在看起来像这样:
CREATE PROCEDURE SP_MyStoreProc ([Multiple Parameters], @returnVal int output)
存储过程的最后一行是:
return @returnVal
我的C#代码现在看起来像这样:( db是我的dbContext类的一个实例)
System.Data.Objects.ObjectParameter identityParameter = new System.Data.Objects.ObjectParameter("returnVal", 0); db.SP_MyStoredProc([Multiple Parameters], identityParameter); int myNewIdentity = Convert.ToInt32(identityParameter.Value);
context.Database.ExecuteSqlCommand
返回命令执行结果而不是查询结果。 如果需要获取数据而不是使用context.Database.SqlQuery
。
SET @ReturnVal=SCOPE_IDENTITY()
然后使用select。
示例: 如何在存储过程中使用DbContext.Database.SqlQuery