ASP.NET Core 2 Controller PUT method failing with Concurrency Core

asp.net-core entity-framework entity-framework-core

Question

I have an ASP.NET Core 2.0 Site that has a scaffolded controller built directly from a simple model and simple context. I seeded the data by simply checking for the number of records in the GET method and if 0, then I added 100 records. GET is retrieving records as I would expect repeatedly.

I'm using the inmemory database provider.

services.AddDbContext<MyDbContext>
            (opt => opt.UseInMemoryDatabase("CodeCampInMemoryDb"));

When I do a PUT with a record that I know existed in my GET, I get a concurrency error as shown at the bottom of this post. I've not used this method of changing the EntityState of a record I created myself, so I'm not sure how this was suppose to work in the first place, but clearly now it is not working.

Maybe it has something to do with a transaction being processed on the inmemory database? I'm not sure how to avoid that if that is the problem.

// PUT: api/Sessions/5
[HttpPut("{id}")]
public async Task<IActionResult> PutSessionRec([FromRoute] int id, [FromBody] SessionRec sessionRec)
{
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != sessionRec.Id)
        {
            return BadRequest();
        }

        _context.Entry(sessionRec).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException xx)
        {
            if (!SessionRecExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
}

Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: Attempted to update or delete an entity that does not exist in the store. at Microsoft.EntityFrameworkCore.Storage.Internal.InMemoryTable`1.Update(IUpdateEntry entry) at Microsoft.EntityFrameworkCore.Storage.Internal.InMemoryStore.ExecuteTransaction

1
0
4/13/2018 10:06:01 PM

Popular Answer

If you marked a property as a Timestamp and don't provide it, you will get this exception every time. You either need to load the entity with the latest Timestamp and update that (not ideal) or you have to send the Timestamp down to the client and have the client send it back up (correct way). However, if you are using an older version of JSON serialization, you have to convert the byte[] to base 64 and then convert it back.

0
4/14/2018 7:11:49 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow