3

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)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
CMS
  • 3,657
  • 1
  • 27
  • 46

3 Answers3

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:

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • As someone coming from RoR to C#, it baffles me that something this simple can't be done out of the box with EF. – rgoliveira Mar 16 '18 at 14:09
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)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jelleB
  • 153
  • 1
  • 2
  • 10
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 .