3

What is the equal code in EntityFramework to this sql code?

select Scope_Identity()

I want to get the id of the last record that i have inserted to database in EF.

WishToBePro
  • 183
  • 1
  • 2
  • 11
  • 1
    You can't directly invoke that SQL function. However, if you define your table's column to be based on an `INT IDENTITY` field, EF should automatically update your entity object with the new value after the data has been inserted into SQL Server – marc_s Apr 13 '11 at 08:09

1 Answers1

3

You must ensure that your key property is mapped with StoreGeneratedPattern.Identity (here you can find some more about this setting). This should be used as default when generating the model from MS SQL database where the key column is defined with IDENTITY. After that it is enough to call SaveChanges on the context and the key property will be automatically filled for you.

riQQ
  • 9,878
  • 7
  • 49
  • 66
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670