Setting batch size in Entity Framework Core

Entity Framework (pre-core) didn’t support batching of CUD statements, so if you were inserting 100 entities for example, EF sent 100 statements across the wire which isn’t ideal from a latency point of view.

Thankfully Entity Framework Core supports batching by default. Prior to Entity Framework Core 5, there was no default batch size so this was limited by the DB platform itself.

Since 5.0 the EF team have set the batch size to 42 which they found was optimal for many common scenarios. There’s likely however to be a ‘sweet spot’ for your specific application of perhaps between 20-50 inserts per statement which gives the best performance.

There’s a lot of factors at play so its really a matter of trial and error to see what performs best. Setting the batch size too low will result in too many round-trips whereas if the batch size is set too high there will be less roundtrips but performance could still be poor as the larger query will take more time to run on the DB server.

Setting the batch size is easy and is done in the OnConfiguring method. In the below example I’ve instructed EF Core to update no more than 50 entities in each SQL statement.

EF Core Batching

Note from above you can see I’ve also set MinBatchSize which means batching will only kick in when there’s at least 5 entities to update. If there’s less than 5 items to be updated separate queries will be sent by EF Core. In most cases you can safely ignore this setting as EF will trigger batching of entities at around 3-7 entities anyhow.

Leave a Reply

Your email address will not be published. Required fields are marked *