Search code examples
.net-coreef-core-3.1

How to select & update a single field using EF Core 3.1


How to implement this feature like:

UPDATE BlogSite
SET PostCount = PostCount + 1
WHERE BlogId = @BlogId

base on entity framework 3.1 (MySQL)


Solution

  • Addition to @sadullah's answer,

    In order to make it atomic and performant, I suggest you to wrap it by a transaction since you are having two db operations (select, update). And also you might want to consider using async versions of efcore's functions.

    using (var transaction = await _yourDbContext.Database.BeginTransactionAsync())
    {
        var entry = await _yourDbContext.BlogSite.FindAsync(*);
        entry.PostCount++;
        await _yourDbContext.SaveChangesAsync();
    
        await transaction.CommitAsync();
    }