Entity Framework 1 Flashcards
What is the purpose of IModelCustomizer? Give the declaration of the interface.
Performs additional configuration of the model in addition to what is discovered by convention.
public interface IModelCustomizer
{
public void Customize(ModelBuilder modelBuilder, DbContext context);
}
What is the use case of IModelCustomizer?
It’s useful when you want to change the model, but have no access to the DbContext implementation code.
This is why this interface is used very often by database providers and different extensions, but almost never used in application code.
How to replace the default IModelCustomizer implementation with your own?
You can call ReplaceService method of DbContextOptionsBuilder.
The object is accessible as a parameter when you call AddDbContext on IServiceCollection.
Example:
builder.ReplaceService<IModelCustomizer, MyModeCustomizer>();
What is the lifetime of IModelCustomizer? What are the implications of that?
The service lifetime is Singleton.
Implications:
- This means a single instance is used by many DbContext instances.
- The implementation must be thread-safe.
- This service cannot depend on services registered as Scoped.
What is the recommendation when you replace the IModelCustomizer implementation?
When replacing this service consider deriving the implementation from ModelCustomizer or RelationalModelCustomizer to preserve the default behavior.
What ModelCustomizer, one of the default implementations of IModelCustomizer, does?
Builds the model for a given context. This implementation builds the model by calling OnModelCreating(ModelBuilder) on the context.
What RelationalModelCustomizer, one of the default implementations of IModelCustomizer, does?
It’s kind of strange, but it just inherits ModelCustomizer and has no additional logic.