Compiled models
Starting from version 6, Entity Framework Core introduced the possibility to create precompiled data structures that improve Entity Framework Core’s performance by about 10 times in the case of models with hundreds of entities (see the reference in the Further reading section for more details). This step is accomplished by generating some code that, once compiled together with the data layer project, creates data structures that our context classes can use to improve performance.
The usage of pre-compilation is advised just after you verify the system experiences slow-downs and also on very simple queries. In other words, it is better to start without pre-compilation and then possibly add it in case of slow-downs caused by the EF infrastructure.
Code is generated with the Optimize-DbContext
command provided by the Microsoft.EntityFrameworkCore.Tool
NuGet package that we already installed. The command accepts the folder name to place the code and the namespace to place all classes. In our case, let’s choose the Optimization
folder and the WWTravelClubDB.Optimization
namespace:
Optimize-DbContext -Context MainDBContext -OutputDir Optimization -Namespace WWTravelClubDB.Optimization
Here, the –Context
parameter must be passed the name of our context class. The Optimization
folder is automatically created and filled with classes.
The optimization code depends on the ORM configuration, so the Optimize-DbContext
command must be repeated each time a new migration is created.
Optimizations are enabled by passing the root of our optimization model as an option when an instance of the context class is created. Let’s open the LibraryDesignTimeDbContextFactory.cs
file and add the line below:
builder.UseSqlServer(connectionString);
//Line to add. Add it after that the optimization model has been created
builder.UseModel(Optimization.MainDbContextModel.Instance);
return new MainDbContext(builder.Options);
Now, you are ready to interact with the database through Entity Framework Core.