EF Core add new record, assigned identity when life cycle is scoped

babak fakhriloo 41 Reputation points
2021-02-28T17:21:14.217+00:00

Hi

In asp.net core 3.0 app with ef core 3.18, dbcontext registered AsScoped, when a new record created with identity set as integer and incremental, and automatic number identity value is assigned to that entity record, say 1, if at the same time in another scope creates a new record and dbcontext has picked 1 for the identity value, when the records are committed ("SaveChanges") the assgined values for identities will change definitely!

So my question here is that I can not count on that generated id until SaveChanges is called ? and I have to access that entity record object to read exact value of identity record ?

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
753 questions
0 comments No comments
{count} votes

Accepted answer
  1. Wade Gausden 166 Reputation points
    2021-03-07T00:48:17.777+00:00

    Hi there,

    I think there is some confusion over who "picks" the identity. The DbContext does not infact pick the identity, the database does. When you call SaveChanges, Entity Framework inserts the records into the database, the database "picks" the identity, and returns that identity back to EntityFramework to populate on your model.

    So to your particular question :

    if at the same time in another scope creates a new record and dbcontext has picked 1 for the identity value

    This will not happen as the database controls identity, and even if two requests are being handled concurrently by your application and being inserted into the database, the database will handle this for you and not pick clashing identities.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,626 Reputation points
    2021-03-01T06:23:57.437+00:00

    Hi babakfakhriloo,
    EF 6 and EF Core both, automatically populates the DB-generated Id properties (primary key or foreign key) when you call the SaveChanges() method.
    And you can get ID only after saving, instead you can create a new Guid and assign before saving.
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.