0

How can i transform this sql query to an EF linq command

"update dbo.table set col1= col1 + 1 where Id = 27" 

i want to execute this query using one command to avoid concurrency problems in case of another client modify the record in the same time

i'm looking for doing that using EF but in one command

i tried this but i'm looking for a better solution :

context.table1.FromSqlInterpolated($"update dbo.table  set col1= col1+ 1 where Id=27").FirstOrDefaultAsync();
CSharp-n
  • 140
  • 7

3 Answers3

2

I would propose to use linq2db.EntityFrameworkCore (note that I'm one of the creators)

Then you can do that with ease:

await context.table1.Where(x => x.Id == 27)
   .Set(x => x.Col1, prev => prev.Col1 + 1)
   .UpdateAsync();
Svyatoslav Danyliv
  • 13,476
  • 1
  • 9
  • 23
1

There are ways to update a column without first querying, but the problem you have is that the update is based on the existing value.

Entity Framework can't help you there. You can only do what you want with a direct SQL statement.

Gabriel Luci
  • 33,807
  • 4
  • 44
  • 75
0

Even the original SQL statement should be executed within a transaction if you want to be sure no other changes can occur between reading and updating the value. It's one SQL statement, but the db still has to read the value, increment and store.

pjs
  • 228
  • 1
  • 6