c# - EF Core with SQLite on xamarin:如何删除数据库并通过代码重新运行迁移
问题描述
在我的应用程序中可以重置数据库,以便服务器的同步将再次下载所有数据。在使用 EF Core 之前,我只会删除数据库文件并重新创建它,现在,使用 EF Core,我不确定该怎么做,如果我执行 EnsureDeleted,.Migrate() 之后将不起作用。如果我手动删除数据库文件, .Migrate() 也不会工作......
所以,我试过这个:
using (var model = new XSModel(false, false))
{
model.Database.EnsureDeleted();
}
using (var model = new XSModel(false, false))
{
model.Database.Migrate();
}
迁移抛出:
Microsoft.Data.Sqlite.SqliteException: 'SQLite Error 14: 'unable to open database file'.'
asdfsadfas
我试过这个:
var filePath = new Java.IO.File(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "dbname.db"));
if (filePath.Exists())
filePath.Delete();
using (var model = new XSModel(false, false))
{
model.Database.Migrate();
}
并且随着这个迁移也抛出:
Microsoft.Data.Sqlite.SqliteException: 'SQLite Error 14: 'unable to open database file'.'
解决方案
我现在在 EF Core 3.x 中这样做的方式是:
public bool UpdateDatabase(bool ensureDeleted)
{
var success = true;
if (ensureDeleted)
{
using (var unitOfWork = this.CreateScope(false, false))
{
unitOfWork.EnsureDeleted();
unitOfWork.DbContext.GetDependencies().StateManager.ResetState();
this.ContextDataSettings.IsFirstInitializationCompleted = false;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
try
{
using (var unitOfWork = this.CreateScope(false, false))
success = unitOfWork.MigrateDatabase();
}
catch (Exception e)
{
if (!ensureDeleted)
{
this.UpdateDatabase(true);
return success;
}
this._logger.Error(e, "Could not migrate");
throw;
}
return success;
}
推荐阅读
- php - laravel 在数据表中显示多个数据
- node.js - 如何迭代包含查询的对象,并全部执行
- android - 无法使用 jniLibs 将 .so 文件添加到 Android Studio 3.5.3
- android - 使用数据绑定和 Kotlin 在 Android 中观察类参数
- google-apps-script - 修改代码 - 删除从单元格引用的一行数据。Google Apps 脚本/Google 表格
- javascript - 如何在 laravel 表视图刀片中显示来自 JSON 的指定对象值
- php - 将网站A的内容显示到网站B而不重定向
- flutter - 固定大小的可滚动容器中的长文本颤动
- dynamics-crm - 在更改字段值时选择业务流程阶段
- java - 哈希图。查找两个哈希映射之间具有相同值的键