.NET Maui Blazor混合应用中System.Data.SQLite.EF6.dll的AOT编译错误
我正在开发一个使用SQLite的.NET Maui Blazor应用,在Release模式构建时遇到了AOT(Ahead of Time)编译相关错误。错误信息如下:
Precompiling failed for \obj\Release\net7.0-android\android-x86\linked\System.Data.SQLite.EF6.dll with exit code 1. Mono Ahead of Time compiler - compiling assembly \obj\Release\net7.0-android\android-x86\linked\System.Data.SQLite.EF6.dll Using profile data file 'C:\Program Files\dotnet\packs\Microsoft.Maui.Sdk\7.0.86\Sdk\maui.aotprofile' Using profile data file 'C:\Program Files\dotnet\packs\Microsoft.Maui.Sdk\7.0.86\Sdk\maui-blazor.aotprofile' Failed to load method 0x600015b from '\obj\Release\net7.0-android\android-x86\linked\System.Data.SQLite.EF6.dll' due to Could not load file or assembly 'System.Data.SQLite, Version=1.0.117.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139' or one of its dependencies.. Run with MONO_LOG_LEVEL=debug for more information. AOT of image obj\Release\net7.0-android\android-x86\linked\System.Data.SQLite.EF6.dll failed.
已尝试确保所需程序集存在、清理并重新生成解决方案等措施,但问题仍未解决。禁用整个解决方案的AOT后构建正常,但希望保留AOT以获取性能优势。尝试通过在数据库项目的.csproj文件中添加<EnableAOT>false</EnableAOT>单独禁用其AOT,却没有效果。想知道:
- 是否有其他开发者遇到类似问题?
- 能否单独禁用单个项目的AOT?
- 或者有其他在启用AOT时解决该错误的建议?
单独跳过指定程序集的AOT编译:.NET Maui的AOT由主应用项目触发,类库项目单独设置
<EnableAOT>false</EnableAOT>无效。可以在主项目的.csproj中添加以下配置,指定跳过AOT的程序集:<PropertyGroup> <AotExcludeAssemblies>System.Data.SQLite.EF6;System.Data.SQLite</AotExcludeAssemblies> </PropertyGroup>这样既能保留大部分代码的AOT优化,又能避开有问题的SQLite相关程序集。
阻止链接器裁剪依赖程序集:Release模式下的链接器可能误删了
System.Data.SQLite的依赖,导致AOT编译时找不到。在主项目的.csproj中添加链接器保留规则:<ItemGroup> <TrimmerRootAssembly Include="System.Data.SQLite" /> <TrimmerRootAssembly Include="System.Data.SQLite.EF6" /> </ItemGroup>也可以创建
Linker.xml文件,写入以下内容:<linker> <assembly fullname="System.Data.SQLite" /> <assembly fullname="System.Data.SQLite.EF6" /> </linker>升级SQLite库版本:当前使用的
1.0.117.0版本可能存在AOT兼容性缺陷,升级到最新稳定版通常能解决这类问题。开启详细日志定位问题:按照错误提示设置环境变量获取更详细的编译日志,执行以下命令构建:
set MONO_LOG_LEVEL=debug dotnet build -c Release从日志中可以精准定位到哪个依赖加载失败,再针对性修复。
切换到官方SQLite驱动:如果上述方法都无效,可以考虑替换为
Microsoft.Data.Sqlite——这是.NET官方维护的SQLite库,对.NET Maui和AOT的兼容性更完善,迁移成本也较低。
内容的提问来源于stack exchange,提问作者Baz

