1

This seems silly, but I cannot find any example code that shows how to retrieve the last inserted id when doing an insert query with ExecuteSqlRaw

var sql = @"INSERT INTO [MyDb-Dev].[dbo].[" + table + "] (...) VALUES (...)";
_context.Database.ExecuteSqlRaw(sql);

How do I retrieve the last inserted id ?

Thanks for your help

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
phil123456
  • 1,192
  • 2
  • 10
  • 26
  • 1
    Pretty sure you can do this with an output parameter. Have a look at this link: https://www.yogihosting.com/stored-procedures-entity-framework-core/ – Andrew Dec 10 '20 at 12:36
  • but how do you get the id of the inserted record to be stored in the output parameter? – phil123456 Dec 10 '20 at 12:40

2 Answers2

0

You can get inserted id with OUTPUT in MS SQL Server.

OUTPUT returns information from, or expressions based on, each row affected by an INSERT, UPDATE, DELETE, or MERGE statement. These results can be returned to the processing application for use in such things as confirmation messages, archiving, and other such application requirements.

var sql = @"INSERT INTO [MyDb-Dev].[dbo].[" + table + "] (...) OUTPUT inserted.Id VALUES (...)";
int returnValue = _context.Database.SqlQuery<int>(sql).FirstOrDefault();
Emin Mesic
  • 1,681
  • 2
  • 8
  • 18
0

add this to the query

;SELECT @LastCreatedId = CAST(SCOPE_IDENTITY() as int)

add a parameter to the call

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

get the value like this

_context.Database.ExecuteSqlCommand(sql3, parameters);
returnValue = (int)returnCode.Value;
phil123456
  • 1,192
  • 2
  • 10
  • 26