5

I'm looking for a way to write code with Entity Framework to update 1000's of records that match a criteria.

In SQL it would look like this

UPDATE [Items] 
SET [IsInSeason] = 1 
WHERE [Name] like '%summer%'

It doesn't make sense for me to load in all items into memory just for this update.

And I would like to avoid writing regular SQL statements (if possible)

4 Answers 4

6

Out of the box, Entity Framework has no such ability. You either need to load the entities before updating, or you need to resort to raw SQL (as an ad-hoc statement, or by calling a stored procedure).

There are a few EF extension packages, however, that claim to support this batch update and batch delete scenario. I haven't had any personal experience with any of them, but give them a look:

Sign up to request clarification or add additional context in comments.

2 Comments

As someone coming from RoR to C#, it baffles me that something this simple can't be done out of the box with EF.
BTW now in latest version of EF core they are adding support to update entities without loading!
1

To work with Entity Framework I believe you have to load the data into memory. How else are you going to give your statements? You could write a stored procedure that you call from your data layer if you really don't want to load the data into memory and just let SQL Server handle it (if you're working with SQL Server)

Comments

0

You can get all items and update them in loop like this

(from x in dataBase.Items
         where x.Name.Contains("summer")
         select x).ToList().ForEach(xx => x.IsInSeason=1);

if you use entity framework ,you should get all items as objects , do the nessecar changes , and save them .

Comments

0

Answer from 2023, we can now use ExecuteUpdate() and ExecuteDelete(), it requires EF Core 7.0. You don't need loop or any previous read.

https://learn.microsoft.com/en-us/ef/core/saving/execute-insert-update-delete

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.