3

I would like to retrieve the inserted ID after executing this command:

db.Database.ExecuteSqlCommand("INSERT INTO Table_Ressources (IdTypeRessource, IdSociete, IdTypeFormatIntitule_UR)Values (1,1,1);

How should I do it please?

Steve Czetty
  • 6,147
  • 9
  • 39
  • 48
  • Here the primary key colum is identity column and it's none of the columns specified here in question? – Chetan Feb 21 '17 at 14:10

3 Answers3

2

You want to use OUTPUT with ExecuteScalar to return the ID of the record INSERTED (or even updated).

INSERT INTO Table_Ressources (IdTypeRessource, IdSociete, IdTypeFormatIntitule_UR) 
OUTPUT INSERTED.Id
VALUES (1,1,1);

The statement will return the ID of the inserted record.

Some reference:

https://msdn.microsoft.com/en-us/library/ms177564.aspx

How do I use an INSERT statement's OUTPUT clause to get the identity value?

Community
  • 1
  • 1
Tony Basallo
  • 3,000
  • 2
  • 29
  • 47
0

Try adding SELECT SCOPE_IDENTITY() to the command, and look at the return value of ExecuteSqlCommand

Tsahi Asher
  • 1,767
  • 15
  • 28
0

You need to use the "ExecuteScalar" instead of "ExecuteSqlCommand". The ExecuteScalar does what you need as explained here:

https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx

Balbinator
  • 220
  • 2
  • 9