Amir
Amir

Reputation: 724

EntityFramework Update with one roundtrip to the database

I have a table as follow:

Contacts:

| Id | Name  | Age |
|----|-------|-----|
| 1  | amir  | 35  |
| 2  | steve | 29  |

And also have POCO entities (detached entity) as follow:

var contacts = new [] {
                        Contact {Id = 1, Age = 34},
                        Contact {Id = 2, Age = 25}
                       };

and then:

using (var ctx = new ApplicationDbContext())
{
    ctx.Contacts.Update(contacts);
    ctx.SaveChanges();
}

What is the best practice to update table rows mentioned at the first with one round-trip database via entity-framework (code first)?
Note: I want to update only Age column.

Upvotes: 0

Views: 1837

Answers (1)

VahidN
VahidN

Reputation: 19136

EF Core supports batching and if you set its batch size to 1, you will get the same result as EF 6.x

optionsBuilder.UseSqlServer(
   @"Server=(localdb)\mssqllocaldb;Database=Demo.Batching;Trusted_Connection=True;",
   options => options.MaxBatchSize(1)
);

Which means you should start using the EF Core instead of EF 6.x, if you want less round trips to the db for insert/update/delete, or you should use 3dr party libraries which support BulkUpdate such as https://github.com/zzzprojects/EntityFramework-Plus

Upvotes: 2

Related Questions