Model Caching

The first time you perform a bulk operation, the database table model is cached to store table information such as:

  • Column name
  • Column type
  • Column nullable
  • Whether the table has a trigger
  • Etc.

This is necessary because some SQL statements generated by the library vary depending on this information.

To retrieve this information, some SQL queries are executed the first time the table is used. These queries read the database schema and build the model used internally.

So, the first time you call a bulk operation for a table, it always takes slightly longer because this information needs to be retrieved and cached.

This behavior happens only once per table (but might happen multiple times for the same table in concurrent scenarios).

Two methods are available to control this behavior:

CacheModel

To optimize caching or control when it happens, you can use the CacheModel method.

This is particularly useful when performing benchmarks to ensure the caching happens outside of the measured code.

Cache all tables found in the model

// @nuget: Z.EntityFramework.Extensions.EFCore
using Z.EntityFramework.Extensions;

context.CacheModel();

Cache a specific entity type

// @nuget: Z.EntityFramework.Extensions.EFCore
using Z.EntityFramework.Extensions;

context.EntitySimples.CacheModel();
context.Set<EntitySimple>().CacheModel();
context.CacheModel<EntitySimple>();
context.CacheModel(typeof(EntitySimple));
context.CacheModel(typeof(EntitySimple), typeof(EntitySimple2));

RefreshModel

If your database table has been modified since it was cached, you will need to refresh the information by calling the RefreshModel method:

context.RefreshModel();

All cached information will be cleared and retrieved again, similar to the first time the model was loaded.

For example, if a column is added dynamically to a table while your application is still running, the cached model will not be aware of this new column. By calling RefreshModel, the model will be rebuilt and include the new column without requiring an application restart.

Summary

By default, the library already handles model caching for you, so you don’t need to do anything.

However, if you want more control, you can:

  • Use CacheModel to ensure the model is cached at the time you choose (for example, before a benchmark or during application startup)
  • Use RefreshModel to clear the cache and reload it if your table schema has been modified

This gives you full control over when the model is cached and refreshed.


Last updated: 2026-05-04
Author:


Contents