1

I have to update every row in a Sql Server table with about 150,000 records using entity framework. To reduce the amount of hits the server takes, I would like to do this in separate batches of 1000 rows. I need entity framework to:

  1. Select the first 1000 rows from the DB.
  2. Update those rows.
  3. Call SaveChanges() method.
  4. Get next 1000 rows.
  5. Repeat.

Whats the best way to achieve this?

I'm using entity framework 4 and SQL Server 2012.

2
  • does this need to happen in a transaction? Commented Sep 13, 2012 at 18:05
  • @DanielA.White Im not sure what you mean Commented Sep 13, 2012 at 18:29

2 Answers 2

4

Use LINQ Skip & Take:

return query.Skip(HOW MUCH TO SKIP -AT THE BEGINNING WILL BE ZERO-)
    .Take(HOW MUCH TO TAKE -THE NUMBER OF YOUR PAGING SIZE-).ToList();

If you want to do it within a loop you can do something like this:

int pagingIncrement = 1000;
for (int i = 0; i <= 150 000; i=i+pagingIncrement)
{
    var query = your actual LINQ query.
    var results = query.Skip(i).Take(pagingIncrement);

    UpdatePartialResults(results);
}

Note: It is important that while updating those rows you don't update the criteria for the ORDER BY within your actual LINQ query, otherwise you could be end up updating the same results again and again (because of the reordering).

Other idea will be to extend the IEnumerable iterator with some of the previously given ideas such as a Skip(counter).Take(pagingSize and yield result (to be processing kinda asynchronously).

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

1 Comment

Could you expand on this? I'm not sure how I would implement this inside a loop.
2

something like this should work:

int skip =0;
int take = 1000;
for (int i = 0; i < 150; i++)
{
var rows = (from x in Context.Table
            select x).OrderBy(x => x.id).Skip(skip).Take(take).ToList();

//do some update stuff with rows

skip += 1000;
}

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.