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

3
  • 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() Commented Dec 8, 2011 at 18:06
  • Thanks Icarus. I never realized that. Guess I should update some of my older apps too! Commented Dec 8, 2011 at 18:10
  • Possible duplicate of How can I get Id of inserted entity in Entity framework? Commented Jun 14, 2016 at 2:01

1 Answer 1

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; 
Sign up to request clarification or add additional context in comments.

4 Comments

I just confirmed that's exactly what it does. Many thanks ob!
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?
How to get Auto Identity Key before Insert via EF?
Guess this is before save changes then how to refetch only ID int newPK = entity.ID;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.