none
DbUpdateConcurrencyException error when saving record in EF Core 1.1 RRS feed

  • Question

  • First of all, sorry if this was posted in the wrong category - I couldn't find an EF category in the options...

    I have an ASP .Net Core 1.1 Web Api using EF Core 1.1
    I have a controller that gets triggered when a post is performed:

    // POST: api/People
    [HttpPost]
    public async Task<IActionResult> PostPerson([FromBody] Person person)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        _context.Person.Add(person);
        await _context.SaveChangesAsync();
        string uri = CreateUri(person.PersonId);
        person.Uri = uri;
        await _context.SaveChangesAsync();
        return CreatedAtAction("GetPerson", new { id = person.Id }, person);
    }

    As you can see, this controller adds a new Person record to the database. It then gets the newly created person's ID number to generate a URI to that person, and saves this URI back to the database. The first SaveChangesAsync() works perfectly and creates a new person record in the database. Immediately after that, the Person object is already automatically populated with the newly created Person ID. However, when I call the second SaveChangesAsync(), I get this error:

    Error Message:
    Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.

    Source:
    "Microsoft.EntityFrameworkCore.Relational"

    Target:
    ThrowAggregateUpdateConcurrencyException

    Stack Trace:
    at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ThrowAggregateUpdateConcurrencyException(Int32 commandIndex, Int32 expectedRowsAffected, Int32 rowsAffected) at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.d__6.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.EntityFrameworkCore.Update.Internal.MySqlModificationCommandBatch.d__19.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.EntityFrameworkCore.Update.Internal.MySqlBatchExecutor.d__1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.d__54.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.d__52.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.EntityFrameworkCore.DbContext.d__35.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at InspectionsWebApi.Controllers.PeopleController.d__5.MoveNext() in C:\Users\fabsr\Source\Repos\InspectionsWebApi\InspectionsWebApi\Controllers\PeopleController.cs:line 78


    More specifically, this appears to be a DbUpdateConcurrencyException error.

    I am the only one accessing the database or using this Web API. I've tried reattaching the object to the context just before the second SaveChangesAsync():

    ...
    person.Uri = uri;
    _context.People.Attach(person);
    await _context.SaveChangesAsync();
    ...

    But same error. I've tried re-fetching this person just after the first SaveChanges():

    ...
    person = _context.People.Find(person.Id);
    person.Uri = uri;
    await _context.SaveChangesAsync();
    ...

    But same error. I've tried this just before the second SaveChanges():

    ...
    var entry = _context.Entry(person);
    entry.Property(e => e.Url).IsModified = true;
    await _context.SaveChangesAsync();
    ...

    but same error...Any ideas? The backend is a MySQL Server database, and I am using the Pomelo framework to talk to the database.



    Thursday, April 20, 2017 1:48 PM

All replies

  • Hi Jpereira1974,

    Based on your description, I create a simple demo with Localdb, it works well. Please check if you personid after the first savechanges method. if you get person id. please modify your code like this and check if it works.

    [HttpPost]
    public async Task<IActionResult> PostPerson([FromBody] Person person)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        _context.Person.Add(person);
        await _context.SaveChangesAsync();
        string uri = CreateUri(person.PersonId);
        person.Uri = uri;
       _context.Entry(person).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
        await _context.SaveChangesAsync();
        return CreatedAtAction("GetPerson", new { id = person.Id }, person);
    }

    Best regards,

    Cole Wu


    MSDN Community Support<br/> Please remember to click &quot;Mark as Answer&quot; the responses that resolved your issue, and to click &quot;Unmark as Answer&quot; if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact <a href="mailto:MSDNFSF@microsoft.com">MSDNFSF@microsoft.com</a>.

    Friday, April 21, 2017 5:05 AM
    Moderator
  • Thanks Cole. Tried your suggestion but I still get the same error
    Friday, April 21, 2017 6:41 AM
  • Hi Jpereira1974,

    Because company's policy, I could not install MySQL on my machine and reproduce your issue on my side, I would suggest that you could post your issue on the following link (gif of Pomelo.EntityFrameworkCore.MySql )

    https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql/issues

    Best regards,

    Cole Wu


    MSDN Community Support&lt;br/&gt; Please remember to click &amp;quot;Mark as Answer&amp;quot; the responses that resolved your issue, and to click &amp;quot;Unmark as Answer&amp;quot; if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact &lt;a href=&quot;mailto:MSDNFSF@microsoft.com&quot;&gt;MSDNFSF@microsoft.com&lt;/a&gt;.

    Thursday, May 4, 2017 7:25 AM
    Moderator