2

I am trying to figure out if there is a way to update multiple rows at once with Entity.

For now I am using Linq2Sql SubmitChanges which will perform an update row by row:

c.PROPERTYONE = valueOne;
c.PROPERTYTWO = valueTwo;
...
dataContext.SubmitChanges();

In my case, valueOne and valueTwo will most likely change for each iteration.

I would like to know if it's possible to store for example, up to 1000 rows and update them at once.

I know how to do it with inserts (by getting the DbContext instance, the appropriate table, calling the Add function then SaveChanges) but I'm struggling in finding the equivalent for updates.

Thanks in advance!

2

3 Answers 3

8

You should use the following concept to update multiple rows.

using (var db = new MyDbContext())
{
var myData=db.YourTableObject.Where(x=>x.Someproperty=="Something").ToList();
myData.ForEach(m => m.YouPropertye= "Set Your Value",m.SomeOther="Set Other");
db.SaveChanges()

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

1 Comment

The problem with this solution is that the records are first read and loaded into memory, then they are updated. It would need a way to update them without having to dump them.
2

In Entity Framework, you can use transaction. So you can group all changes in one transaction. When you commit a transaction then all changes go together/ can be rollback together. I stole the example from here https://msdn.microsoft.com/en-us/library/dn456843(v=vs.113).aspx

  using (var dbContextTransaction = context.Database.BeginTransaction()) 
                { 
                    try 
                    { 
                        context.Database.ExecuteSqlCommand( 
                            @"UPDATE Blogs SET Rating = 5" + 
                                " WHERE Name LIKE '%Entity Framework%'" 
                            ); 

                        var query = context.Posts.Where(p => p.Blog.Rating >= 5); 
                        foreach (var post in query) 
                        { 
                            post.Title += "[Cool Blog]"; 
                        } 

                        context.SaveChanges(); 

                        dbContextTransaction.Commit(); 
                    } 
                    catch (Exception) 
                    { 
                        dbContextTransaction.Rollback(); 
                    } 
                } 

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.