首页 > 解决方案 > How to make Sqlite work in Windows 10 at the publication

问题描述

有一个经典的应用,其中使用了微软的Entity Framework Core.Sqlite,尝试通过Windows 10部署发布应用,抛出异常:DllNotFoundException: Unable to load DLL "e_sqlite3": the specified module could not be found。(来自 HRESULT 的异常:0x8007007E)

尝试将 e_sqlite3 库添加到“Windows 应用程序打包项目”中,最终出现以下异常:SQLite 错误 14: 'unable to open database file' with EF Core code first

我尝试了在 Internet 上找到的不同解决方案,但没有一个我不适合。

开发环境:Windows 10、Visual Studio 2017、Microsoft.EntityFrameworkCore.Sqlite 2.2.1.0 和 Microsoft.Data.Sqlite 2.2.1.0

标签: cwpfsqlite

解决方案


这是我解决这两个问题的方法。

第一个问题是本机 e_sqlite3.dll 文件未复制到 Package 项目的输出中。Package 项目在 Microsoft.DesktopBridge.targets 中具有 MSBuild 逻辑,该逻辑正在调用其每个引用项目(例如 WPF 项目)的 GetCopyToOutputDirectoryItems 目标。由于 e_sqlite3.dll 文件通过 NuGet 包包含在引用的项目中,因此包含它们的方式不会导致 GetCopyToOutputDirectoryItems 目标拾取它们。我通过将以下代码添加到我的 WPF 项目中来解决此问题:

  <Target Name="IncludeNativeBinariesAsOutput" BeforeTargets="GetCopyToOutputDirectoryItems">
    <ItemGroup>
      <Content Include="$(OutputPath)\x64\e_sqlite3.dll">
        <Link>x64\e_sqlite3.dll</Link>
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      </Content>
      <Content Include="$(OutputPath)\x86\e_sqlite3.dll">
        <Link>x86\e_sqlite3.dll</Link>
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      </Content>
    </ItemGroup>

    <AssignTargetPath Files="@(Content)" RootFolder="$(MSBuildProjectDirectory)">
      <Output TaskParameter="AssignedFiles" ItemName="ContentWithTargetPath" />
    </AssignTargetPath>
  </Target>

下一个问题是在必要的本机文件位于它们需要的位置之后出现“无法打开数据库文件”错误。我认为这是因为它试图在 Windows 包项目不支持的位置创建项目。我通过设置一个特殊的值来处理这个问题,SqliteConnection 寻找该值来构造数据库文件的路径。在执行任何数据库操作之前,我刚刚将此行添加到我的 App 构造函数类中。

AppDomain.CurrentDomain.SetData("DataDirectory", ApplicationData.Current.LocalFolder.Path);

推荐阅读