Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

EF Core - problem with optimistic concurrency

$
0
0

Hi,

I`ve got problem with optimistic concurrency while updating entity in the EF Core. As far as I know I properly added RowVersion to my model and during the UPDATE this property shows in the WHERE clause:

UPDATE [ServiceItems] SET [CreatedAt] = @p0, [CreatedById] = @p1, [GrossValueAdded] = @p2, [IsArchived] = @p3, [IsBlocked] = @p4, [IsManual] = @p5, [IsSubNamePrinted] = @p6, [IsSuspended] = @p7, [IsValueVariable] = @p8, [Name] = @p9, [NetValue] = @p10, [Notes] = @p11, [Quantity] = @p12, [RemoteSystemServiceCode] = @p13, [ServiceCategoryType] = @p14, [ServiceItemCustomerSpecificTag] = @p15, [SpecificLocation] = @p16, [SubName] = @p17, [UpdatedAt] = @p18, [UpdatedById] = @p19, [VATRate] = @p20, [InstallationDate] = @p21, [IsInvoiced] = @p22, [ServiceItemsSetId] = @p23
WHERE [Id] = @p24 AND [RowVersion] = @p25;

However If I`m trying to update the same entity during two simultaneous sessions no exception is thrown.  Then I decided to to mess up with the RowVersion like below and still no excpetion is thrown during UPDATE.

        // PUT api/OneTimeServiceItems/5
        [HttpPut("{id}")]
        public async Task<IActionResult> Put(int id, [FromBody]OneTimeServiceItemDto updatedOneTimeServiceItemDto)
        {
            if (!ModelState.IsValid || updatedOneTimeServiceItemDto.Id != id)
                return BadRequest();

            var oneTimeServiceItems = await _context.ServiceItems.OfType<OneTimeServiceItem>().Where(g => g.Id == id).ToListAsync();

            if (!oneTimeServiceItems.Any())
                return NotFound();

            var updatedOneTimeServiceItem = oneTimeServiceItems.First();

            Mapper.Map(updatedOneTimeServiceItemDto, updatedOneTimeServiceItem);

            updatedOneTimeServiceItem.RowVersion[7]++; // HERE I WANT TO FORCE EF TO THROW EXCEPTION

            try
            {
                _context.ServiceItems.Update(updatedOneTimeServiceItem);
                await _context.SaveChangesAsync();
            }
            catch (Exception exception)
            {
                BadRequest(exception);
            }

            return new NoContentResult();
        }

Could someone tell what I`m doing wrong in that code?


Viewing all articles
Browse latest Browse all 1698

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>