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;
Share:
63,113

Related videos on Youtube

chrisg229
Author by

chrisg229

Updated on October 27, 2020

Comments

  • chrisg229
    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
      Icarus over 12 years
      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()
    • chrisg229
      chrisg229 over 12 years
      Thanks Icarus. I never realized that. Guess I should update some of my older apps too!
    • Michael Freidgeim
      Michael Freidgeim almost 8 years
  • chrisg229
    chrisg229 over 12 years
    I just confirmed that's exactly what it does. Many thanks ob!
  • Mahesh
    Mahesh over 8 years
    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?
  • Revathi Vijay
    Revathi Vijay about 6 years
    How to get Auto Identity Key before Insert via EF?
  • Pratik 1020
    Pratik 1020 over 4 years
    Guess this is before save changes then how to refetch only ID int newPK = entity.ID;