Get Auto Identity Key after Insert via EF
63,113
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;
Related videos on Youtube
Author by
chrisg229
Updated on October 27, 2020Comments
-
chrisg229 over 3 years
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
-
Icarus over 12 yearsI just want to point out that
SELECT @@Identity
is NOT a good way to get the last inserted id. You should useSCOPE_IDENTITY()
-
chrisg229 over 12 yearsThanks Icarus. I never realized that. Guess I should update some of my older apps too!
-
Michael Freidgeim almost 8 yearsPossible duplicate of How can I get Id of inserted entity in Entity framework?
-
-
chrisg229 over 12 yearsI just confirmed that's exactly what it does. Many thanks ob!
-
Mahesh over 8 yearsWhen 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?
-
Revathi Vijay about 6 yearsHow to get Auto Identity Key before Insert via EF?
-
Pratik 1020 over 4 yearsGuess this is before save changes then how to refetch only ID int newPK = entity.ID;