[英]How to create a password protected database?
I am trying to create a password protected SQLite database to use within a WPF application using Entity Framework Core.我正在尝试创建一个受密码保护的 SQLite 数据库,以便在使用 Entity Framework Core 的 WPF 应用程序中使用。
I know how to generate DbContext and Entities from an existing database but don't know how to create a password protected database.我知道如何从现有数据库生成 DbContext 和实体,但不知道如何创建受密码保护的数据库。 What is the difference between an encrypted database and a password protected database?
加密数据库和密码保护数据库有什么区别?
According to this article and this issue , there is no way (yet?) to encrypt the database using the Microsoft.Data.Sqlite assembly (used by EF Core
). 根据这篇文章和这个问题 ,没有办法(还是?)使用Microsoft.Data.Sqlite程序集(由
EF Core
使用)加密数据库。
Based on this, here is what I've done to get it working with EF Core
: 基于此,以下是我为使其与
EF Core
一起工作所做的工作:
while configuring your dbContext, give the optionsBuilder
your own DbConnection
: 在配置dbContext时,为
optionsBuilder
您自己的DbConnection
:
var conn = new SQLiteConnection(@"Data Source=yourSQLite.db;"); conn.Open(); var command = conn.CreateCommand(); command.CommandText = "PRAGMA key = password;"; command.ExecuteNonQuery(); optionsBuilder.UseSqlite(conn);
It is very important to use the SQLiteConnection
(which can manage encrypted database) from the System.Data.SQLite.Core
assembly and not the SqliteConnection
from Microsoft.Data.Sqlite
. 从
System.Data.SQLite.Core
程序集使用SQLiteConnection
(可以管理加密数据库)而不是Microsoft.Data.Sqlite
的SqliteConnection
非常重要。
According to the article, you could probably used the built in SqliteConnection
by replacing the sqlite3.dll
shipped within the Microsoft.Data.Sqlite
assembly by another one that handle encrypted database (you can find a free one on this repo ). 根据这篇文章,你可以使用内置的
SqliteConnection
,将Microsoft.Data.Sqlite
程序SqliteConnection
的sqlite3.dll
替换为另一个处理加密数据库的程序(你可以在这个repo上找到一个免费的)。 But I did not tested it. 但我没有测试过它。
I was pleasantly surprised with how smooth the solution described here was for me.我对 这里描述的解决方案对我来说如此顺利感到惊喜。
Navigate to the github repo and scroll down to the steps.导航到github 存储库并向下滚动到步骤。
Install/remove the NuGet in steps 1 to 4.在步骤 1 到 4 中安装/移除 NuGet。
Modify your DbContext bit:修改您的 DbContext 位:
public class MyDbContext: DbContext { public MyDbContext(): base() {} protected override void OnConfiguring(DbContextOptionsBuilder builder) { SqliteConnectionStringBuilder builder = new SqliteConnectionStringBuilder(); builder.DataSource = @"myDatabase.db"; builder.Password = "myPassword"; optionsBuilder.UseSqlite(new SqliteConnection(builder.ConnectionString)); } //... and some other unrelated stuff... }
Some notes :一些注意事项:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.