How to find an identity of the last inserted row in Entity Framework?

Entity Framework will automatically load the last inserted id to populate the primary key column of the inserted entity:

var customer = new Customer { Name = "Steven" };

context.AddObject(customer);

context.SaveChanges();

var id = customer.Id;

Note that the Id property only gets populated after calling SaveChanges() in case the StoreGeneratedPattern attribute is set to “Identity” or “Computed” for the auto-incremented ID column in the Storage part of the model.

Leave a Comment