Entity Framework and SCOPE_IDENTITY

非 Y 不嫁゛ 提交于 2019-12-02 01:56:46

Declare a output type of parameter in your procedure definition:

 create procedure [dbo].[Procedurename] @returnVal int output
 as 
 SET @returnVal = SCOPE_IDENTITY();

and while calling the stored procedure call it as:

 declare @returnVal int
 exec Procedurename @returnVal output
 print @returnVal 

taken from the OPs question

Adding an output parameter worked (answer marked below).

The stored procedure signature looks like this now:

My stored procedure signature now looks like this:

CREATE PROCEDURE SP_MyStoreProc ([Multiple Parameters], @returnVal int output)

The last line of the stored procedure is:

return @returnVal

My C# code looks like this now: (db is an instance of my dbContext class)

System.Data.Objects.ObjectParameter identityParameter = 
new System.Data.Objects.ObjectParameter("returnVal", 0);

db.SP_MyStoredProc([Multiple Parameters], identityParameter);

int myNewIdentity = Convert.ToInt32(identityParameter.Value);
Bassam Alugili

context.Database.ExecuteSqlCommand return the command executing result and not the query result. If you need to get data than use context.Database.SqlQuery.

SET @ReturnVal=SCOPE_IDENTITY() and then use the select.

Example: How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!