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

sqlite数据库使用广泛,在net core中也自然也得到支持,当我使用如下代码直接打开数据库链接时报错了,System.Exception:“You need to call SQLitePCL.raw.SetProvider(). If you are using a bundle package, this is done by calling SQLitePCL.Batteries.Init().”自认为写的代码很简单也没有错误。示例代码是net core3.

var connStr = @"";//连接字符串
                var conn = new SqliteConnectionStringBuilder(connStr)
                {
                    DataSource = "TestSqlite.sqlite",
                    Mode = SqliteOpenMode.ReadWriteCreate,
                    Password = "password"
                }.ToString();//使用这个方式设置密码,避免sql注入

                var connection = new SqliteConnection(conn);//创建SQLite连接
                if (connection.State == ConnectionState.Closed)
                {
                    connection.Open();
                    var createTableSqlStr = @"CREATE TABLE  if not exists ""Alarm"" ( ""Id"" INTEGER NOT NULL, ""AlarmName"" TEXT, ""AlarmTypeId"" INTEGER, PRIMARY KEY ( ""Id"" ) );";
                    var result = connection.Execute(createTableSqlStr);//使用Dapper执行sql语句创建表
                    Console.ReadKey();
                }

原因就是我们在net core 3中只使用了Microsoft.EntityFrameworkCore.Sqlite.Core 或者只引用了 Microsoft.Data.Sqlite.Core ,缺少相关实现。解决办法是添加引用Microsoft.EntityFrameworkCore.Sqlite,自从net core3 开始我们操作sqlite官方提供的标准库就是Microsoft.EntityFrameworkCore.Sqlite 了,和2.0版本有点不同。

https://www.lebang2020.cn/details/210317xmn4btjq.html

posted on 2022-08-16 14:05  糯米白白  阅读(5696)  评论(2编辑  收藏  举报

导航