Programmatically set Entity Framework batch size

The default batch size in Entity Framework is 42. This may be ideal in some cases but for others you might want it to be lower or higher depending on the situation. It’s useful therefore to be able to set this when we create our DbContext so it can be use case dependent.

This is easy to do with simple changes to our DbContext class…

All we have done above is to create a non default constructor which sets a private property which is used in the MaxBatchSize setting in the OnConfiguring method. This means we can create DbContexts like below…


Note that if you’re working in the Database First approach you should subclass the generated context and add your customizations into the subclass otherwise you’ll lose your changes each time you re-scaffold.

The general idea is below…

Leave a Reply

Your email address will not be published.