Entity Framework Retrieve Inserted Id Discover about IDENTITY
How can I get Id of inserted entity?
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?
StackOverflow Related Questions
- How can I get Id of inserted entity in Entity framework?
- Get Record ID in Entity Framework after insert
Answer
It is pretty easy. If you are using DB generated Ids (like IDENTITY
in MS SQL) you just need to add entity to the contexct and call SaveChanges on that context. Id will be automatically filled for you.
using (var context = new EntityContext()) { var customer = new Customer() { Name = "John" }; context.Customers.Add(customer); context.SaveChanges(); int id = customer.CustomerID; }
Entity framework by default follows each INSERT
with SELECT SCOPE_IDENTITY()
when auto-generated Ids are used.
ZZZ Projects