官方文档:
https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-6.0/whatsnew#compiled-models
优势:
- improve EF Core startup time for applications with large models.
- Startup time means the time to perform the first operation on a DbContext when that DbContext type is used for the first time in the application. Note that just creating a DbContext instance does not cause the EF model to be initialized. Instead, typical first operations that cause the model to be initialized include calling
DbContext.Add
or executing the first query. - A large model typically means 100s to 1000s of entity types and relationships.
- Startup time means the time to perform the first operation on a DbContext when that DbContext type is used for the first time in the application. Note that just creating a DbContext instance does not cause the EF model to be initialized. Instead, typical first operations that cause the model to be initialized include calling
- Compiled models are created using the
dotnet ef
command-line tool. Ensure that you have installed the latest version of the tool before continuing. - The
--output-dir
and--namespace
options can be used to specify the directory and namespace into which the compiled model will be generated.- The output from running this command includes a piece of code to copy-and-paste into your DbContext configuration to cause EF Core to use the compiled model.
- multiple compiled models can be generated for DbContext types that may use different models depending on some runtime configuration
-
Compiled models have some limitations:
- Global query filters are not supported.
- Lazy loading and change-tracking proxies are not supported.
- Custom IModelCacheKeyFactory implementations are not supported. However, you can compile multiple models and load the appropriate one as needed.
- The model must be manually synchronized by regenerating it any time the model definition or configuration change.
-
Because of these limitations, you should only use compiled models if your EF Core startup time is too slow. Compiling small models is typically not worth it.
If supporting any of these features is critical to your success, then please vote for the appropriate issues linked above.
-