0
votes

I got this error, but im unable to determine what is the real cause, therefore im unable to fix it? "Entity Framework Core: A second operation started on this context before a previous operation completed"

The context

private readonly ApplicationDbContext _context;

public MyController(ApplicationDbContext context) 
{
    _context = context;
}

The error occurs here "await _context.SaveChangesAsync();", however this statement is executed only once.

        //Find user by Id
        var foundUser = await _context.Users.FindAsync(myUserId);

        //Populate myUserData here
         ....

        //If user not found, create the user
        if (foundUser == null)
        {
            _context.Users.Add(myUserData);
            await _context.SaveChangesAsync(); //<--------ERROR HERE!
        }
1
Likely unrelated, but in this pattern how is _context disposed? - Eric J.
The code above is in a method, and I was using it without "await" , I added "await" and everything is working now. - 001

1 Answers

0
votes

You are trying to modify foundUser , but it's not returned yer becuase it's async.

The easier way to fix this is using .Result like this:

if (foundUser.Result == null)

This way it will wait for the result of the previous call