Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How to get id of inserted entity in entity framework?


Asked by Rhea Knox on Dec 03, 2021 FAQ



How can I get Id of inserted entity in Entity framework? 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.
Also,
The ID is generated by the database after the row is inserted to the table. You can't ask the database what that value is going to be before the row is inserted. You have two ways around this - the easiest would be to call SaveChanges.
Indeed, Entity framework by default follows each INSERT with SELECT SCOPE_IDENTITY () when auto-generated Id s are used.
And,
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.
Moreover,
EF is really about exposing data as .NET objects. It includes handling a "graph" of objects that is you should be able: When you'll call SaveChanges, EF shpuld be able to start from the customer object you loaded using the context and find all changes including the new address and its child contacts.