实体框架核心 SQLite 连接字符串关键字不受支持:版本

Eti*_*and 10 c# sqlite entity-framework-core

我使用 SQLite 数据库使用 .NET Core 2.2 创建了一个 ASP.NET MVC 网站。到目前为止,它运行良好。当我想将特定于 SQLite 的关键字添加到连接字符串时,问题就开始了,例如

Data Source=~\\App_Data\\MyDb.db; Version=3; DateTimeFormat=UnixEpoch; DateTimeKind=Utc
Run Code Online (Sandbox Code Playgroud)

现在我得到

不支持关键字:'版本'

我像这样注册数据库

// ConfigureServices(IServiceCollection services)
var conn = Configuration.GetConnectionString("MyDB").Replace("~", _env.ContentRootPath);
services.AddDbContext<MyDBContext>(options => options.UseSqlite(conn));
Run Code Online (Sandbox Code Playgroud)

然后 MyDBContext 有

public partial class MyDBContext : DbContext
{
    public MyDBContext() { }

    public SatrimonoContext(DbContextOptions<MyDBContext> options)
        : base(options) { }

    public virtual DbSet<Book> Book { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后我在我的页面模型中使用它

private SatrimonoContext _db;

public BookAccuracyListModel(SatrimonoContext dbContext)
{
    _db = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
}
Run Code Online (Sandbox Code Playgroud)

从那里我可以通过 LINQ 正常访问 _db。

在这里发帖之前,我对该主题进行了大量研究,我发现最好的回应是这个

此提供程序是 Microsoft.Data.Sqlite。这些连接字符串用于 System.Data.SQLite。

我们支持以下关键字:缓存、数据源、模式。

我遇到的问题是因为我试图创建一个 SqlConnection 而不是 SQLiteConnection。做出改变解决了我的问题。

但是,如果我做得“正确”,我就不会创建 SqlConnection,因此无法将其更改为 SQLiteConnection。另一个响应不包括解决方案。

那么我该如何让它以正确的方式工作呢?

Bar*_*r J 8

Github 中有一个关于这个问题的线程。

Microsoft.Data.Sqlite 只支持三个关键字:

  • 缓存-私有或共享
  • 数据源-数据库文件。可以是 URI 文件名。
  • 模式- ReadWriteCreate、ReadWrite、ReadOnly 或 Memory。

此命名空间不支持其他关键字,但是如果您使用System.Data.SQLite命名空间中提到的关键字,它将起作用,因为它们是与System.Data.SQLite.

你的两个选择:

  1. Version=3从连接字符串中删除关键字或任何其他不受支持的关键字
  2. 更改用于SQLite连接的命名空间。


Eti*_*and 5

扩展 Barr 的响应,解决方案是将 System.Data.SQLite.Core 添加到项目中。

然后更换

var conn = Configuration.GetConnectionString("Satrimono").Replace("~", _env.ContentRootPath);
services.AddDbContext<SatrimonoContext>(options => options.UseSqlite(conn));
Run Code Online (Sandbox Code Playgroud)

var connString = Configuration.GetConnectionString("Satrimono").Replace("~", _env.ContentRootPath);
var conn = new SQLiteConnection(connString);
services.AddDbContext<SatrimonoContext>(options => options.UseSqlite(conn));
Run Code Online (Sandbox Code Playgroud)

就是这样!