gpt4 book ai didi

c# - SQLite 与 MVC 核心

转载 作者:行者123 更新时间:2023-11-30 16:40:17 28 4
gpt4 key购买 nike

我正在尝试在内存中创建数据库并使用 .NET Core 2.1 框架运行查询。为此,我安装了一个名为 Microsoft.Data.Sqlite.Core 的包,然后尝试执行以下操作:

var connection = new SqliteConnection("Data Source=:memory:");
connection.Execute("Some Create Table Query");

我的代码会因以下错误而崩溃:

You need to call SQLitePCL.raw.SetProvider(). If you are using a bundle package, this is done by calling SQLitePCL.Batteries.Init().

我进行了大量挖掘以找到解决方案,其中一个建议调用它:

SQLitePCL.raw.SetProvider(new SQLite3Provider_e_sqlite3());

这会产生一个新错误:

'Unable to load DLL 'e_sqlite3' or one of its dependencies: The specified module could not be found. (Exception from HRESULT: 0x8007007E)'

在这一点上我真的迷失了如何完成这个。我想要做的就是创建一个内存数据库,以便我可以运行一些查询以进行单元测试。

我不确定这是否相关,但我没有使用 EF6,我使用的是 Dapper,而且我在实际项目中使用的是 SQL Server。我想在单元测试中插入 Sqlite,这样我也可以测试我的查询。

我觉得我使用了错误的包,但环顾四周,我找不到任何关于如何将 Sqlite 与 MVC 核心项目一起使用的明确文档。

最佳答案

尝试添加 SQLitePCLRaw.bundle_green打包到你的项目中。

dotnet add package SQLitePCLRaw.bundle_green

此时,以下程序 ( inspired by this) 工作:

using Microsoft.Data.Sqlite;

class Program
{
static void Main()
{
var connection = new SqliteConnection("Data Source=:memory:");
connection.Open();

var createCommand = connection.CreateCommand();
createCommand.CommandText =
@"
CREATE TABLE data (
value TEXT
)
";

createCommand.ExecuteNonQuery();
}
}

这是我在本地运行的测试。

cd C:/temp
dotnet new console
dotnet add package Microsoft.Data.Sqlite.Core
dotnet add package SQLitePCLRaw.bundle_green
//
// paste the above program into Program.cs, then...
//
dotnet run

什么是 bundle_green? bundle_green 是 Sqlite“ bundle ”之一,专门用于简化跨平台开发。这是来自 the official repository 的描述:

These packages automatically bring in the right dependencies for each platform. They also provide a single Init() call that is the same for all platforms... SQLitePCLRaw.bundle_green is a bundle that uses e_sqlite3 everywhere except iOS, where the system-provided SQLite is used.

关于c# - SQLite 与 MVC 核心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51575892/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com