【EF Core 】在 EF Core 6.0 中,你可以生成已编译的模型(compiled models)

发布时间 2023-03-30 10:23:44作者: 小林野夫

在 EF Core 6.0 中,你可以生成已编译的模型(compiled models)。当你有一个大的模型,而你的 EF Core 启动很慢时,这个功能是有意义的。你可以使用 CLI 或包管理器控制台来做。

public class ExampleContext : DbContext
{
    public DbSet<Person> People { get; set; }
 
    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseModel(CompiledModelsExample.ExampleContextModel.Instance)
        options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=SparseColumns;Trusted_Connection=True;");
    }
}
public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

CLI:

dotnet ef dbcontext optimize -c ExampleContext -o CompliledModels -n CompiledModelsExample

Package Manager Console:

Optimize-DbContext -Context ExampleContext -OutputDir CompiledModels -Namespace CompiledModelsExample
案例:Optimize-DbContext -Context PrimarydataContext -OutputDir CompiledModels -Namespace CompiledModelsExample

 PrimarydataContext是dbContext

然后,将【CompiledModelsExample.PrimarydataContextModel.Instance】提示的代码配置到到dbcontext上:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .UseModel(CompiledModelsExample.PrimarydataContextModel.Instance)
        .UseSqlite(@"Data Source=test.db");

 

 

 

 

 

更多关于已编译模型及其限制的介绍:

https://devblogs.microsoft.com/dotnet/announcing-entity-framework-core-6-0-preview-5-compiled-models/
https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-6.0/whatsnew#limitations