0

I'm using ASP.NET MVC Core 1.1 with VS2015. I would like to understand the following in a portion of my controller code: The last line of the following code gives the error: There is already an open DataReader associated with this Command which must be closed first.. But if I change SaveChangesAsync() to SaveChanges() code works fine.

Snapshot of Controller:

public IActionResult myActionMethod(...)
{
    ...
    var oRecToUpdate = _context.Order.Where(c => c.OrdersId == 104).SingleOrDefault();
    if (oRecToUpdate != null)
    {
        oRecToUpdate.Price = 98.09;
        _context.SaveChangesAsync();
    }

    string sStateNumer = _context.StateNames
        .Where(s => s.State == "myState").Select(t => t.StateNumber).SingleOrDefault();
    ....
}
DavidG
  • 113,891
  • 12
  • 217
  • 223
nam
  • 21,967
  • 37
  • 158
  • 332

1 Answers1

3

Because you are calling an asynchronous method on the context, it's potentially still running by the time you get to the next query. You need to await the call to prevent this:

await _context.SaveChangesAsync();

Or call the non-asynchronous version:

_context.SaveChanges();
DavidG
  • 113,891
  • 12
  • 217
  • 223
  • I should have pointed out that the signature of my action method is not using `async` keyword. It's simply `Public IActionResult myActionMethod(...){...}`. But VS2015 does not complain about using `_context.SaveChangesAsync();` without `await`. I've just added that to my code above – nam Mar 02 '17 at 17:00
  • Why would it complain? It's syntactically correct, but semantically wrong. Resharper would tell you there's an issue though. – DavidG Mar 02 '17 at 17:03