Entity Framework v8, on SaveChangeAsyc() intserts record twice

Reema George Dass 20 Reputation points
2025-03-12T13:41:09.5866667+00:00
  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.

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2025-03-13T06:21:20.2366667+00:00

    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.