0

I am inserting records in database using stored procedures like below

db.Database.ExecuteSqlCommand("sp_insertNewRecord");

Now I want to get the Id of last inserted record.

Due to some reason I can't use below function

db.TableName.Add(record);
db.SaveChanges();

So please don't suggest me to use this.

Meer
  • 656
  • 9
  • 18
  • 4
    Change the stored procedure to output the ID you need, either by returning it or setting it on an output parameter. – David Jul 12 '17 at 10:42
  • 4
    Get your SP to return [SCOPE_IDENTITY()](https://stackoverflow.com/questions/5228780/how-to-get-last-inserted-id) – Liam Jul 12 '17 at 10:44
  • Due to some(**what?**) reason I can't use below function – Lei Yang Jul 12 '17 at 10:50
  • I'd imagine the SP does more than insert into a single table. @LeiYang Or a SQL admin wants all inserts from SPs, etc. This is not uncommon – Liam Jul 12 '17 at 10:51

1 Answers1

4

Create an output variable in your stored procedure like

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

After inserting the record get the SCOPE_IDENTITY() and set that into an OUTPUT variable.

and get the id in entity framework while calling stored procedure.

Hope this help!