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;
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?


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

void SaveChanges() {
    foreach entity in this.entitySet {
        if (isIdentityPK(entity) && !hasPKValue(entity)) {
            executeSQL("INSERT INTO ... VALUES (...)");
            id = executeSQL("LAST_INSERT_ID()");
            setEntityPKValue(entity, id);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.