Update statement with Entity Framework
Asked Answered
H

4

8

Simple question, is it possible to achieve this query this with Entity Framework when updating one entity?

update test set value = value + 1 where id = 10
Hildy answered 16/3, 2009 at 20:12 Comment(0)
N
5

Not really under this form no.

You will have to select all entities that match your criteria, foreach over them and update them.

If you are looking for something that will do it right in the DB because your set could be huge, you will have to use SQL directly. (I don't remember if EF has a way to execute UPDATE queries directly the way Linq To SQL does).

Nesto answered 16/3, 2009 at 20:28 Comment(2)
Just what i suspected, i'll use a sprocHildy
Or you might be able to use this: weblogs.asp.net/pwelter34/archive/2011/11/29/…Guardrail
A
11

Use the Batch Update feature of the Entity Framework Extended Library, like this:

dbContext.Tests.Update(t => t.Id == 10, t => new Test() { Value = t.Value + 1 });
Annal answered 17/12, 2013 at 2:27 Comment(1)
MutantNinjaCodeMonkey mentioned this library in a comment on a different answer. I found the library fit the bill so well that it was worth calling attention to in its own separate answer.Annal
N
5

Not really under this form no.

You will have to select all entities that match your criteria, foreach over them and update them.

If you are looking for something that will do it right in the DB because your set could be huge, you will have to use SQL directly. (I don't remember if EF has a way to execute UPDATE queries directly the way Linq To SQL does).

Nesto answered 16/3, 2009 at 20:28 Comment(2)
Just what i suspected, i'll use a sprocHildy
Or you might be able to use this: weblogs.asp.net/pwelter34/archive/2011/11/29/…Guardrail
R
3

It should be, it will just be a little bit more constrained generally.

var myEntity = context.First(item => item.id == 10);
myEntity.value += 1;
context.SaveChanges();

Should produce similar SQL, you can watch the profiler to see what SQL is actually being generated, but it should be very similar to your statement.

Rutherfordium answered 16/3, 2009 at 20:16 Comment(1)
The EF-generated SQL is quite different: two SQL statements, which are not atomic.Annal
E
1

Since Entity Framework Core 7 you can do this:

await context.Tests.Where(c => c.Id == 10).ExecuteUpdateAsync(
    s => s.SetProperty(b => b.Value, b => b.Value + 1));

More information: https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-7.0/whatsnew#basic-executeupdate-examples

Excited answered 6/9, 2023 at 14:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.