EntityFramework Update with one roundtrip to the database

c# entity-framework entity-framework-6

Question

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.

1
0
1/28/2018 9:58:51 PM

Accepted Answer

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

2
1/28/2018 10:03:59 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow