47

Is there a straight forward way of retrieving a DB auto generated primary key when adding a record via Entity Framework 4.1?

For example:

dbcontext.Entity_Tables.Add(new Entity_Table { item1 = val1, item2 = val2 });
dbcontext.SaveChanges();
newPK = ???;

The SQL equivalent would be:

newPK = executeOnDB("INSERT INTO Entity_Table (item1, item2) VALUES (val1, val2);SELECT @@Indentity";);

BTW I'm using MySQL but the SQL would be the same as on MSSQL

Scotty.NET
  • 12,533
  • 4
  • 42
  • 51
chrisg229
  • 909
  • 2
  • 7
  • 21
  • 6
    I just want to point out that `SELECT @@Identity` is NOT a good way to get the last inserted id. You should use `SCOPE_IDENTITY()` – Icarus Dec 08 '11 at 18:06
  • Thanks Icarus. I never realized that. Guess I should update some of my older apps too! – chrisg229 Dec 08 '11 at 18:10
  • Possible duplicate of [How can I get Id of inserted entity in Entity framework?](http://stackoverflow.com/questions/5212751/how-can-i-get-id-of-inserted-entity-in-entity-framework) – Michael Freidgeim Jun 14 '16 at 02:01

1 Answers1

96

I believe EF should update your entity object with the identity:

var entity = new Entity_Table { item1 = val1, item2 = val2 };
dbcontext.Entity_Tables.Add(entity);
dbcontext.SaveChanges();
int newPK = entity.ID;
Omer Bokhari
  • 57,458
  • 12
  • 44
  • 58
  • 4
    I just confirmed that's exactly what it does. Many thanks ob! – chrisg229 Dec 08 '11 at 18:19
  • 3
    When I insert, there is an InsertBefore trigger on the table which adds its own properties, and so, even if save changes is executing, that insert is replaced by the insert before, and so, the ID returned for me is 0, and the actual value of ID is something else. In that case how do i get the value? – Mahesh Dec 07 '15 at 18:13
  • 2
    How to get Auto Identity Key before Insert via EF? – Revathi Vijay Apr 20 '18 at 06:54
  • Guess this is before save changes then how to refetch only ID int newPK = entity.ID; – Pratik 1020 Sep 09 '19 at 18:27