Files
OptixServe/OptixServe.Infrastructure/EFCore-NativeAOT-Intergration.md
Huxley Deng eb021576a5 [Failed] Try to implement NativeAOT support.
Add: NativeAOT support with EF Core. However failed for compiled binary throw Exception in queries. Wait for a stable support for NativeAOT.

Add: document for intergration EF Core with NativeAOT.
2025-07-11 16:07:14 +08:00

2.2 KiB

EFCore Intergration

Introduction

This app relies on EF Core to access the database.

However, it is NOT so smooth when work with NativeAOT.

To use EF Core, see below.

DesignTimeDbContextFactory

To work with NativeAOT, a code-defined way to create DbContext instance is a MUST in nearly ALL operations of EF Core, letting ef tool discover the DbContext.

In this project, OptixServe.Infrastructure/Utilites/DesignTimeDbContextFactory.cs is set up to do this.

This class implements a simple commandline arguments parser, enabling passing arguments along with dotnet ef.

Currently, there are two options, --config/-c and --data-dir/-d are supported. See documents there.

To pass arguments/options to CreateDbContext static method, pass the arguments following with dotnet ef command, with two dashes splitting.

For example:

dotnet ef database update -- -c ../data/appsettings.Development.json -d ../data/

Workflow

To make the code work, following the steps:

  1. Implement other parts
  2. Compile the data models, with --nativeaot option.
  3. Add migration
  4. Update database
  5. Build project, and Run!

Here are the details.

Requirements

See https://learn.microsoft.com/en-us/ef/core/performance/nativeaot-and-precompiled-queries

Compile Models

dotnet ef dbcontext optimize --output-dir Data/CompiledModels --precompile-queries --nativeaot -- -c ../data_dev/appsettings.Development.json -d ../data_dev/

If this is the first time to run dbcontext optimize, DO NOT forget to UseModel in DbContext construction.

public static void ConfigureDbContext(DbContextOptionsBuilder options)
{
    // ...
    options.UseSqlite(connectionString, b => b.MigrationsAssembly("OptixServe.Infrastructure"))
        .UseModel(AppDbContextModel.Instance);
    // ...
}

Add Migration

dotnet ef migrations add InitialCreate -- -c ../data_dev/appsettings.Development.json

Update Database

dotnet ef database update -- -c ../data_dev/appsettings.Development.json -d ../data_dev/

Build Project

dotnet publish -c Release -r linux-x64