I have a problem with Entity Framework in ASP.NET. I want to get the Id value whenever I add an object to database. How can I do this?
According to Entity Framework the solution is:
using (var context = new EntityContext()) { var customer = new Customer() { Name = "John" }; context.Customers.Add(customer); context.SaveChanges(); int id = customer.CustomerID; }
This doesn't get the database table identity, but gets the assigned ID of the entity, if we delete a record from the table the seed identity will not match the entity ID.
EF execute each INSERT command followed by SELECT scope_identity() statement. SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. The above example will execute the following SQL in the database. WHERE @@ROWCOUNT = 1 AND [StudentID] = scope_identity();
You can retreive an ID before calling . SaveChanges() by using the Hi/Lo alhorithm. The id will be assigned to the object once it is added to dbcontext.
Returns. The number of state entries written to the underlying database.
It is pretty easy. If you are using DB generated Ids (like IDENTITY
in MS SQL) you just need to add entity to ObjectSet
and SaveChanges
on related ObjectContext
. Id
will be automatically filled for you:
using (var context = new MyContext()) { context.MyEntities.Add(myNewObject); context.SaveChanges(); int id = myNewObject.Id; // Yes it's here }
Entity framework by default follows each INSERT
with SELECT SCOPE_IDENTITY()
when auto-generated Id
s are used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With