首页 > 解决方案 > 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'.'

标签: c#androidsqlitexamarinef-core-2.2

解决方案


我现在在 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;
    }

推荐阅读