efcore icon indicating copy to clipboard operation
efcore copied to clipboard

[AOT] ```dotnet ef dbcontext optimize --precompile-queries --nativeaot``` fails with error CS9137

Open digital88 opened this issue 1 year ago • 8 comments

Bug description

Hello.

Trying to run dotnet ef dbcontext optimize --precompile-queries --nativeaot fails with errors. Project is setup to be AOT compatible.

Also, publish fails with the same error.

dotnet publish --ucr Test.Api/Test.Api.csproj -c Release -o ./app

Tools version:

dotnet ef --version
Entity Framework Core .NET Command-line Tools
9.0.4

Full csproj

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <LangVersion>latest</LangVersion>
    <RootNamespace>Test.Api</RootNamespace>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <InvariantGlobalization>true</InvariantGlobalization>
    <PublishAot>true</PublishAot>
    <RuntimeIdentifiers>linux-x64;linux-arm64;osx-arm64;</RuntimeIdentifiers>
    <NuGetAudit>false</NuGetAudit>
    <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
    <Features>InterceptorsPreview</Features>
    <InterceptorsNamespaces>$(InterceptorsPreviewNamespaces);Microsoft.EntityFrameworkCore.GeneratedInterceptors</InterceptorsNamespaces>
    <InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Microsoft.Extensions.Configuration.Binder.SourceGeneration</InterceptorsPreviewNamespaces>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="FluentValidation" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" >
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tasks" >
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" />
    <PackageReference Include="Riok.Mapperly" ExcludeAssets="runtime" PrivateAssets="all" />
    <PackageReference Include="ZiggyCreatures.FusionCache" />
    <PackageReference Include="ZiggyCreatures.FusionCache.Backplane.StackExchangeRedis" />
    <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" />
    <PackageReference Include="Microsoft.Extensions.Configuration" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Binder" />
    <PackageReference Include="Microsoft.DotNet.ILCompiler" />
  </ItemGroup>

</Project>

Your code

Reproduce repo here: https://github.com/digital88/web-api-aot-fc/tree/main

Run command as described in readme. Also fails when using docker:

docker build -t test-api:latest .

Stack traces

Build started...
Build succeeded.
Query precompilation is an experimental feature and should be used with caution.
NativeAOT support is experimental and can change in the future.
Successfully generated a compiled model, it will be discovered automatically, but you can also call 'options.UseModel(TodosContextModel.Instance)'. Run this command again when the model is modified.
System.InvalidOperationException: Compilation failed with errors:
Microsoft.Extensions.Configuration.Binder.SourceGeneration/Microsoft.Extensions.Configuration.Binder.SourceGeneration.ConfigurationBindingGenerator/BindingExtensions.g.cs(38,10): error CS9137: The 'interceptors' experimental feature is not enabled in this namespace. Add '<InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Microsoft.Extensions.Configuration.Binder.SourceGeneration</InterceptorsPreviewNamespaces>' to your project.
Microsoft.Extensions.Configuration.Binder.SourceGeneration/Microsoft.Extensions.Configuration.Binder.SourceGeneration.ConfigurationBindingGenerator/BindingExtensions.g.cs(39,10): error CS9137: The 'interceptors' experimental feature is not enabled in this namespace. Add '<InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Microsoft.Extensions.Configuration.Binder.SourceGeneration</InterceptorsPreviewNamespaces>' to your project.

   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.PrecompileQueries(String outputDir, DbContext context, String suffix, IServiceProvider services, IReadOnlyDictionary`2 memberAccessReplacements, ISet`1 generatedFileNames)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.Optimize(String outputDir, String modelNamespace, String suffix, Boolean scaffoldModel, Boolean precompileQueries, DbContext context, Boolean optimizeAllInAssembly, Boolean nativeAot, List`1 generatedFiles, HashSet`1 generatedFileNames)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.Optimize(String outputDir, String modelNamespace, String contextTypeName, String suffix, Boolean scaffoldModel, Boolean precompileQueries, Boolean nativeAot)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OptimizeContextImpl(String outputDir, String modelNamespace, String contextType, String suffix, Boolean scaffoldModel, Boolean precompileQueries, Boolean nativeAot)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OptimizeContext.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Compilation failed with errors:
Microsoft.Extensions.Configuration.Binder.SourceGeneration/Microsoft.Extensions.Configuration.Binder.SourceGeneration.ConfigurationBindingGenerator/BindingExtensions.g.cs(38,10): error CS9137: The 'interceptors' experimental feature is not enabled in this namespace. Add '<InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Microsoft.Extensions.Configuration.Binder.SourceGeneration</InterceptorsPreviewNamespaces>' to your project.
Microsoft.Extensions.Configuration.Binder.SourceGeneration/Microsoft.Extensions.Configuration.Binder.SourceGeneration.ConfigurationBindingGenerator/BindingExtensions.g.cs(39,10): error CS9137: The 'interceptors' experimental feature is not enabled in this namespace. Add '<InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Microsoft.Extensions.Configuration.Binder.SourceGeneration</InterceptorsPreviewNamespaces>' to your project.

Verbose output

Build succeeded.
dotnet exec --depsfile /Users/<...>/projects/gh/web-api-aot-fc/Test.Api/bin/Debug/net9.0/Test.Api.deps.json --additionalprobingpath /Users/<...>/.nuget/packages --runtimeconfig /Users/<...>/projects/gh/web-api-aot-fc/Test.Api/bin/Debug/net9.0/Test.Api.runtimeconfig.json /Users/<...>/.dotnet/tools/.store/dotnet-ef/9.0.4/dotnet-ef/9.0.4/tools/net8.0/any/tools/netcoreapp2.0/any/ef.dll dbcontext optimize --output-dir ./Migrations/EfModel --precompile-queries --nativeaot --assembly /Users/<...>/projects/gh/web-api-aot-fc/Test.Api/bin/Debug/net9.0/Test.Api.dll --project /Users/<...>/projects/gh/web-api-aot-fc/Test.Api/Test.Api.csproj --startup-assembly /Users/<...>/projects/gh/web-api-aot-fc/Test.Api/bin/Debug/net9.0/Test.Api.dll --startup-project /Users/<...>/projects/gh/web-api-aot-fc/Test.Api/Test.Api.csproj --project-dir /Users/<...>/projects/gh/web-api-aot-fc/Test.Api/ --root-namespace Test.Api --language C# --framework net9.0 --nullable --working-dir /Users/<...>/projects/gh/web-api-aot-fc --verbose
Query precompilation is an experimental feature and should be used with caution.
NativeAOT support is experimental and can change in the future.
Using assembly 'Test.Api'.
Using startup assembly 'Test.Api'.
Using application base '/Users/<...>/projects/gh/web-api-aot-fc/Test.Api/bin/Debug/net9.0'.
Using working directory '/Users/<...>/projects/gh/web-api-aot-fc/Test.Api'.
Using root namespace 'Test.Api'.
Using project directory '/Users/<...>/projects/gh/web-api-aot-fc/Test.Api/'.
Remaining arguments: .
Finding DbContext classes...
Using environment 'Development'.
Finding IDesignTimeDbContextFactory implementations...
Finding DbContext classes in the project...
Found DbContext 'TodosContext'.
Finding application service provider in assembly 'Test.Api'...
Finding Microsoft.Extensions.Hosting service provider...
Using application service provider from Microsoft.Extensions.Hosting.
Using context 'TodosContext'.
Finding design-time services referenced by assembly 'Test.Api'...
Finding design-time services referenced by assembly 'Test.Api'...
No referenced design-time services were found.
Finding design-time services for provider 'Npgsql.EntityFrameworkCore.PostgreSQL'...
Using design-time services from provider 'Npgsql.EntityFrameworkCore.PostgreSQL'.
Finding IDesignTimeServices implementations in assembly 'Test.Api'...
No design-time services were found.
Successfully generated a compiled model, it will be discovered automatically, but you can also call 'options.UseModel(TodosContextModel.Instance)'. Run this command again when the model is modified.
System.InvalidOperationException: Compilation failed with errors:
Microsoft.Extensions.Configuration.Binder.SourceGeneration/Microsoft.Extensions.Configuration.Binder.SourceGeneration.ConfigurationBindingGenerator/BindingExtensions.g.cs(38,10): error CS9137: The 'interceptors' experimental feature is not enabled in this namespace. Add '<InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Microsoft.Extensions.Configuration.Binder.SourceGeneration</InterceptorsPreviewNamespaces>' to your project.
Microsoft.Extensions.Configuration.Binder.SourceGeneration/Microsoft.Extensions.Configuration.Binder.SourceGeneration.ConfigurationBindingGenerator/BindingExtensions.g.cs(39,10): error CS9137: The 'interceptors' experimental feature is not enabled in this namespace. Add '<InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Microsoft.Extensions.Configuration.Binder.SourceGeneration</InterceptorsPreviewNamespaces>' to your project.

   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.PrecompileQueries(String outputDir, DbContext context, String suffix, IServiceProvider services, IReadOnlyDictionary`2 memberAccessReplacements, ISet`1 generatedFileNames)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.Optimize(String outputDir, String modelNamespace, String suffix, Boolean scaffoldModel, Boolean precompileQueries, DbContext context, Boolean optimizeAllInAssembly, Boolean nativeAot, List`1 generatedFiles, HashSet`1 generatedFileNames)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.Optimize(String outputDir, String modelNamespace, String contextTypeName, String suffix, Boolean scaffoldModel, Boolean precompileQueries, Boolean nativeAot)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OptimizeContextImpl(String outputDir, String modelNamespace, String contextType, String suffix, Boolean scaffoldModel, Boolean precompileQueries, Boolean nativeAot)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OptimizeContext.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Compilation failed with errors:
Microsoft.Extensions.Configuration.Binder.SourceGeneration/Microsoft.Extensions.Configuration.Binder.SourceGeneration.ConfigurationBindingGenerator/BindingExtensions.g.cs(38,10): error CS9137: The 'interceptors' experimental feature is not enabled in this namespace. Add '<InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Microsoft.Extensions.Configuration.Binder.SourceGeneration</InterceptorsPreviewNamespaces>' to your project.
Microsoft.Extensions.Configuration.Binder.SourceGeneration/Microsoft.Extensions.Configuration.Binder.SourceGeneration.ConfigurationBindingGenerator/BindingExtensions.g.cs(39,10): error CS9137: The 'interceptors' experimental feature is not enabled in this namespace. Add '<InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Microsoft.Extensions.Configuration.Binder.SourceGeneration</InterceptorsPreviewNamespaces>' to your project.

EF Core version

9.0.4

Database provider

Npgsql.EntityFrameworkCore.PostgreSQL

Target framework

.NET 9.0

Operating system

macOS Ventura (M1 arm64)

IDE

Visual Studio Code + C# dev kit

digital88 avatar Apr 13 '25 21:04 digital88

Unless I'm mistaken, the interceptors feature graduated out of preview and the csproj directive has been renamed from < InterceptorsPreviewNamespaces > to <InterceptorsNamespaces> (specs); though the error you posted above shows the old, preview name (are you using an old SDK?).

In any case, this is a setup issue in your own csproj, and not something related to EF specifically.

roji avatar Apr 14 '25 06:04 roji

Unless I'm mistaken, the interceptors feature graduated out of preview and the csproj directive has been renamed from < InterceptorsPreviewNamespaces > to <InterceptorsNamespaces> (specs); though the error you posted above shows the old, preview name (are you using an old SDK?).

In any case, this is a setup issue in your own csproj, and not something related to EF specifically.

Thanks for reply.

Unfortunately this also fails with same errors:

<InterceptorsNamespaces>$(InterceptorsPreviewNamespaces);Microsoft.EntityFrameworkCore.GeneratedInterceptors;Microsoft.Extensions.Configuration.Binder.SourceGeneration</InterceptorsNamespaces>

-- or

<InterceptorsNamespaces>$(InterceptorsNamespaces);Microsoft.EntityFrameworkCore.GeneratedInterceptors;Microsoft.Extensions.Configuration.Binder.SourceGeneration</InterceptorsNamespaces>

I tried all combinations of properties in csproj, all of them fail. The error is always the same and I can't figure out whats wrong from error's text. Why it's emitting old property is also a mystery to me.

I'm using latest sdk:

dotnet --list-sdks                                                                                                                          
6.0.428 [/usr/local/share/dotnet/sdk]
8.0.402 [/usr/local/share/dotnet/sdk]
8.0.405 [/usr/local/share/dotnet/sdk]
9.0.100 [/usr/local/share/dotnet/sdk]
9.0.200 [/usr/local/share/dotnet/sdk]
9.0.203 [/usr/local/share/dotnet/sdk]

Added this, also didn't change anything.

global.json
{
    "sdk": {
        "version": "9.0.200"
    }
}

Packages.props

<?xml version="1.0" encoding="utf-8"?>
<Project>
  <PropertyGroup>
    <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
  </PropertyGroup>
  <ItemGroup>
    <PackageVersion Include="FluentValidation" Version="11.11.0" />
    <PackageVersion Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
    <PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.4" />
    <PackageVersion Include="Microsoft.EntityFrameworkCore.Tasks" Version="9.0.4" />
    <PackageVersion Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="9.0.4" />
    <PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
    <PackageVersion Include="Riok.Mapperly" Version="4.2.0" />
    <PackageVersion Include="ZiggyCreatures.FusionCache" Version="2.2.0-preview-1" />
    <PackageVersion Include="ZiggyCreatures.FusionCache.Backplane.StackExchangeRedis" Version="2.2.0-preview-1" />
    <PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="3.11.0" />
    <PackageVersion Include="Microsoft.Extensions.Configuration" Version="9.0.4" />
    <PackageVersion Include="Microsoft.Extensions.Configuration.Binder" Version="9.0.4" />
    <PackageVersion Include="Microsoft.DotNet.ILCompiler" Version="9.0.4" />
  </ItemGroup>
</Project>

digital88 avatar Apr 14 '25 07:04 digital88

Ok. Found working csproj. Running dotnet ef dbcontext optimize --precompile-queries --nativeaot still errors, but it seems to generate compiled model at least?

This allows me to build and publish AOT

dotnet publish --ucr Test.Api/Test.Api.csproj -c Release -o ./app

I forgot to mention, previously publish also failed with same errors. I edited OP.

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <LangVersion>latest</LangVersion>
    <RootNamespace>Test.Api</RootNamespace>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <InvariantGlobalization>true</InvariantGlobalization>
    <PublishAot>true</PublishAot>
    <SelfContained>true</SelfContained>
    <RuntimeIdentifiers>linux-x64;linux-arm64;osx-arm64;</RuntimeIdentifiers>
    <NuGetAudit>false</NuGetAudit>
    <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
    <EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
    <InterceptorsNamespaces>$(InterceptorsNamespaces);Microsoft.EntityFrameworkCore.GeneratedInterceptors;Microsoft.Extensions.Configuration.Binder.SourceGeneration</InterceptorsNamespaces>
    <InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Microsoft.Extensions.Configuration.Binder.SourceGeneration</InterceptorsPreviewNamespaces>
    <Features>InterceptorsPreview</Features>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="FluentValidation" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" >
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <!-- <PackageReference Include="Microsoft.EntityFrameworkCore.Tasks" >
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference> -->
    <PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" />
    <PackageReference Include="ZiggyCreatures.FusionCache" />
    <PackageReference Include="ZiggyCreatures.FusionCache.Backplane.StackExchangeRedis" />
    <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" />
    <PackageReference Include="Microsoft.Extensions.Configuration" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Binder" />
    <PackageReference Include="Microsoft.DotNet.ILCompiler" />
  </ItemGroup>

</Project>

I think maybe Microsoft.EntityFrameworkCore.Tasks package is the problem?

digital88 avatar Apr 14 '25 08:04 digital88

In any case, this is a setup issue in your own csproj, and not something related to EF specifically.

I can confirm that I am currently having the same issue, with exactly the same error message. As a reference, here is my .csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">

    <PropertyGroup>
        <TargetFramework>net9.0</TargetFramework>
        <Nullable>enable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
        <InvariantGlobalization>true</InvariantGlobalization>
        <PublishAot>true</PublishAot>
        <InterceptorsNamespaces>$(InterceptorsNamespaces);Microsoft.EntityFrameworkCore.GeneratedInterceptors;Microsoft.Extensions.Configuration.Binder.SourceGeneration</InterceptorsNamespaces>
        <InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Microsoft.Extensions.Configuration.Binder.SourceGeneration</InterceptorsPreviewNamespaces>
        <Features>InterceptorsPreview</Features>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4"/>
        <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.4"/>
        <PackageReference Include="Microsoft.EntityFrameworkCore.Tasks" Version="9.0.4">
            <PrivateAssets>all</PrivateAssets>
            <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference>
    </ItemGroup>

</Project>

I also tried every possible combinations with InterceptorNamespaces and InterceptorsPreviewNamespaces.

dotnet cli version is 9.0.201 (the latest available via winget) and ef tools are on 9.0.4

dotnet --version
9.0.201

dotnet ef --version
Entity Framework Core .NET Command-line Tools
9.0.4

tkappedev avatar Apr 14 '25 16:04 tkappedev

It seems that some dependencies of Microsoft.EntityFrameworkCore.Design are outdated. After adding

<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.13.0" />
<PackageReference Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" Version="4.13.0" />

the compilation succeeds. Those two packages were implicitly installed before as version 4.8.0.

tkappedev avatar Apr 15 '25 07:04 tkappedev

@invalidoperation thanks for that. I don't currently have time to investigate this, but if bumping the versions on these 2 packages works for you, then it's a good workaround. We've already done exactly this for EF 10 (#34637), so that version should be compatible out-of-the-box.

I'll go ahead and close this for now as a good workaround has been found. If there's still trouble here, let me know and we can reopen.

roji avatar Apr 15 '25 07:04 roji

@invalidoperation thanks for that. I don't currently have time to investigate this, but if bumping the versions on these 2 packages works for you, then it's a good workaround. We've already done exactly this for EF 10 (#34637), so that version should be compatible out-of-the-box.

I'll go ahead and close this for now as a good workaround has been found. If there's still trouble here, let me know and we can reopen.

May I suggest adding some footnote with reference to this issue to this docs (repo here)? I was following this documentation when setting up AOT with EF Core. I'm willing to make a PR.

digital88 avatar Apr 15 '25 07:04 digital88

@digital88 sure - feel free to submit a PR.

roji avatar Apr 15 '25 08:04 roji