Share via

Entity Framework v8, on SaveChangeAsyc() intserts record twice

Reema George Dass 0 Reputation points
Mar 12, 2025, 1:41 PM
  public async Task AddAsync<T>(T entity) where T : class
  {
      await _dbContext.Set<T>().AddAsync(entity); // use only context and test
      await _dbContext.SaveChangesAsync();
}

On SaveChangesAsync() 1 duplicate record is inserted.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,340 questions
0 comments No comments
{count} votes

Accepted answer
  1. Hongrui Yu-MSFT 4,930 Reputation points Microsoft External Staff
    Mar 13, 2025, 6:21 AM

    Hi, @Reema George Dass. Welcome to Microsoft Q&A. 

    I am using version 8.0.0 of Entity Framework Core. In my test, the code you provided could be added correctly and is not added twice by mistake.

     

    Please do the following test:

    1.Assuming that you are using a database in Visual Studio 2022 and have turned off the auto-increment of the primary key in the table (here is Identity).Picture4 Then when you execute the AddAsync method, the entity passed in must specify the Id.

    YourEntity entity = new YourEntity() { Id = 1, Name = "AA" };
    

    2.Suppose you have turned on the auto-increment of the primary key in the table.

    Picture5

    Then when you execute the AddAsync method, the entity passed in should not specify the Id.

    YourEntity entity = new YourEntity() {  Name = "AA" };
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    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 additional answers

Sort by: Most helpful

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.