I am trying to update the likecount field using below query. Howver, it gives sytax error
_context.quicknotes.Where(x=>x.Id == request.id).ExecuteUpdate(b=>b.SetProperty(u=>u.LikeCount,u.LikeCount+1));
What is the right way to do it?
I am trying to update the likecount field using below query. Howver, it gives sytax error
_context.quicknotes.Where(x=>x.Id == request.id).ExecuteUpdate(b=>b.SetProperty(u=>u.LikeCount,u.LikeCount+1));
What is the right way to do it?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Lokesh VarmanPosted Jul 23, 2023, 12:59 PM
Based on the code snippet you provided, it looks like you are trying to update the
LikeCountfield of aquicknoteobject using Entity Framework Core. However, Entity Framework Core'sExecuteUpdatemethod does not have a direct equivalent in the EF Core library, which could be the reason for the syntax error.To update the
LikeCountfield in the database, you can follow a different approach using theSaveChangesmethod of yourDbContextafter modifying the entity. Here's how you can do it:Assuming you have a
DbContextclass namedYourDbContext, and the entity class is namedQuicknote, the correct way to update theLikeCountfield is as follows:In this code, we first retrieve the
quicknoteentity with the specifiedIdusingFirstOrDefault. Then, if thequicknoteis found (i.e., not null), we increment itsLikeCountproperty and callSaveChangeson theDbContextto persist the changes to the database.