C# WinForms+EF SQLite部署报错:无法加载e_sqlite3.dll
- 技术栈:C# WinForms + EF Core 8.0.6 + SQLite(首次使用EF管理SQLite)
- 异常现象:Visual Studio中运行应用可正常读写数据库;使用Visual Studio 2022项目安装程序构建.exe并安装后,启动报错:
System.DllNotFoundException: Unable to load DLL 'e_sqlite3' or one of its dependencies - 已尝试操作:安装
SQLitePCLRaw.bundle_e_sqlite3(该包本身已是Microsoft.EntityFrameworkCore.Sqlite的依赖项),但错误未解决 - 打包警告:将目标平台设为x86以兼容32/64位系统时,构建过程出现以下警告:
WARNING: File 'ControlAguaPotable.exe' of project output 'Publish Items from ControlAguaPotable (Active)' targeting 'x64' is not compatible with the project's target platform 'x86'
WARNING: File 'e_sqlite3.dll' of project output 'Publish Items from ControlAguaPotable (Active)' targeting 'Unknown' is not compatible with the project's target platform 'x86'
WARNING: File 'e_sqlite3.dll' of project output 'Publish Items from ControlAguaPotable (Active)' targeting 'Unknown' is not compatible with the project's target platform 'x86'
WARNING: File 'e_sqlite3.dll' of project output 'Publish Items from ControlAguaPotable (Active)' targeting 'x64' is not compatible with the project's target platform 'x86'
- 额外问题:打包过程包含了
libe_sqlite3.so、libe_sqlite3.dylib等非Windows平台文件,构建最终提示成功但存在上述警告
1. 统一项目与安装程序的目标平台
- 主项目配置:右键主项目 → 属性 → 生成 → 平台目标选择
x86,取消勾选“首选32位”(针对.NET Framework);若为.NET 8,直接指定目标平台为x86,清理并重建项目。 - 安装程序配置:右键安装程序项目 → 属性 → 目标平台选择
x86,确保与主项目平台完全一致,避免混合x86/x64导致的文件不兼容。
2. 过滤非Windows平台的SQLite原生库
打开主项目的.csproj文件,添加以下配置,确保只保留Windows x86版本的e_sqlite3.dll,排除其他平台文件:
<ItemGroup> <!-- 移除非Windows平台的SQLite库 --> <Content Remove="runtimes/**/libe_sqlite3.so" /> <Content Remove="runtimes/**/libe_sqlite3.dylib" /> <Content Remove="runtimes/**/libe_sqlite3.bundle" /> <!-- 强制复制x86版本的e_sqlite3.dll到输出目录 --> <None Include="runtimes/win-x86/native/e_sqlite3.dll"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> </None> </ItemGroup>
添加后清理项目的bin、obj目录,重新生成。
3. 调整安装程序的文件包含规则
- 在安装程序项目中,删除自动包含的所有
e_sqlite3.dll实例及非Windows平台文件。 - 手动添加主项目
bin/x86/Release目录下的e_sqlite3.dll到安装程序的“应用程序文件夹”中,确保仅包含x86版本。 - 检查安装程序的“项目输出”设置,确认仅引用主项目的x86架构输出,而非多平台混合输出。
4. 验证打包后的文件完整性
安装完成后,检查应用安装目录是否存在e_sqlite3.dll,可通过Dependency Walker工具确认该文件为x86架构。若文件缺失,需重新检查安装程序的文件包含配置。
内容的提问来源于stack exchange,提问作者Ismael Santana

