1

I want to understand how EF track ID when the primary key is identity. (DB first)

For example

class User
{
 int Id; //auto generated via SQL identity, also the primary key of the table Users.
 string Name;
}
//adding a new user-
User user = new User () {Name="TestUser"};//Id will be 0;
DB.Users.Add(user);
DB.SaveChanges();
user.Id; //Will have value;

More over if I have navigation property with foreign key to the user.Id will be updated as well.

I believe that EF track tables with the primary key, but in this case it is determined by SQL (or w/e) on creation, so how does the EF gets the actual ID after creation?

asked Jan 2, 2017 at 9:20

1 Answer 1

2

I dont know EF, but Hibernate and Doctrine. I assume they are very similar.

EF keeps a reference to the object.

When Add(Object) is called, EF keeps a reference to the object in any case (it is needed to detect changes).

When SaveChanges(), is called, EF goes through all the references it has stored. It sees the User instance and knows that the PK strategy is IDENTITY and that the very instance has no PK value yet; As a result, EF decides to execute an INSERT statement for that instance. It then uses the DB driver to determine the ID of the row it just wrote and writes that value to the property. (Probably with LAST_INSERT_ID()).

Some pseudo code:

void Add(obj) {
 // add the object to the interal set of entities; this will keep track
 this.entitySet.add(obj);
}
void SaveChanges() {
 foreach entity in this.entitySet {
 if (isIdentityPK(entity) && !hasPKValue(entity)) {
 executeSQL("INSERT INTO ... VALUES (...)");
 id = executeSQL("LAST_INSERT_ID()");
 setEntityPKValue(entity, id);
 }
 }
}
answered Jan 2, 2017 at 10:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.