0

How to implement this feature like:

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

base on entity framework 3.1 (MySQL)

Fair
  • 431
  • 1
  • 5
  • 11

2 Answers2

1
// I assume your DBContext object is _db.

var blogSite=_db.BlogSite.Find(BlogId);
blogSite.PostCount++;
_db.SaveChanges();
Sadullah DOĞAN
  • 335
  • 2
  • 10
0

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();
}
denizkanmaz
  • 566
  • 5
  • 9
  • Yes, This is my currently solution, but is there a more simply way in one line code. e.g.: db.Set().Where(u => u.id == 1).UpdateFromQuery(x => new Post { Count = x.Count + 1 }); – Fair Nov 05 '20 at 06:12
  • I had use this package: Z.EntityFramework.Extensions.EFCore – Fair Nov 05 '20 at 06:45
  • Yes, there are ways to handle it with one-line code by using 3rd party dependencies. I wanted to show how to handle it without 3rd party dependencies. However, you can simply wrap the approach above in generic way and can use anywhere you want. ( by the way the package you mention has proprietary license and is not open source meaning that we do not know what approach they are using to handle this under the method `UpdateFromQuery`. See: https://github.com/zzzprojects/EntityFramework-Extensions/tree/master/src ) – denizkanmaz Nov 06 '20 at 09:03
  • hiahia, it's a bad news that it's not open source. Do you have another similar EF extensions? – Fair Nov 06 '20 at 10:00
  • I am not familiar with any of 3rd party EF extensions. However, I believe that you can find something on internet that satisfies your needs. For instance, check this official ms doc page: https://learn.microsoft.com/en-us/ef/core/extensions/ Additionally, seems that you are not the only one who asks this question in stackoverflow.: https://stackoverflow.com/questions/42345300/is-there-a-non-commercial-alternative-to-z-entityframework-extensions – denizkanmaz Nov 06 '20 at 17:32