C# – How does Entity Framework track object with identity as key

cdatabaseentity-frameworkidentity

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?

Best Answer

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);
        }
    }
}
Related Topic