【问题标题】:Xamarin EF Core database migration deletes old dataXamarin EF Core 数据库迁移删除旧数据
【发布时间】:2020-01-25 17:35:40
【问题描述】:

我有一个 Xamarin 移动应用程序,我添加了一些新功能,为此我还添加了新的数据库表。我还为这些创建了一个新的迁移。但是当我运行此迁移时,它实际上会清除数据库中的所有旧数据,而不仅仅是添加表等。

为了创建迁移,我按照 MarkSmith.8123 here 的说明进行操作。实际上,我之前使用相同的说明进行过一次迁移。

要试用它,我首先从 Google Play 安装该应用。我登录,进行一些本地更改,然后关闭应用程序。然后我通过在 Visual Studio 中调试来安装新版本(带有迁移)。当我再次启动应用程序时,所有旧数据都消失了,登录信息和本地更改。我还尝试使用 Visual Studio 从较早的提交(没有新东西)进行第一次安装,没有任何明显的区别。

我正在使用 Microsoft.EntityFrameworkCore.Sqlite 2.0.1。

public class MyDbContext : Microsoft.EntityFrameworkCore.DbContext
{
    ...

    public MyDbContext(string databasePath)
    {
        DatabasePath = databasePath;
        AddInitialMigrationForPreMigrationInstalls();
        Database.Migrate();
    }

    private void AddInitialMigrationForPreMigrationInstalls()
    {
        if (Database.Exists()) // This is just an extension doing: dbFacade.GetService<IRelationalDatabaseCreator>().Exists()
        {
            Database.ExecuteSqlCommand(@"
                CREATE TABLE IF NOT EXISTS ""__EFMigrationsHistory"" (
                    ""MigrationId"" TEXT NOT NULL CONSTRAINT ""PK___EFMigrationsHistory"" PRIMARY KEY,
                    ""ProductVersion"" TEXT NOT NULL
                );

                INSERT OR IGNORE INTO ""__EFMigrationsHistory"" (""MigrationId"", ""ProductVersion"")
                VALUES ('20180829103834_InitialCreate', '2.0.1-rtm-125');        
            ");
        }
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite($"Filename={DatabasePath}");
    }

    ...
}

我希望 db 中的所有数据都保持不变,而新表应该已经添加。

我真的不知道如何进一步检查。我怎样才能看到发生了什么?

【问题讨论】:

    标签: c# sqlite xamarin entity-framework-core entity-framework-migrations


    【解决方案1】:

    Android 应用是沙盒化的。您的侧载应用程序无法访问从 Google Play 商店下载的应用程序的数据库文件。

    当您从之前的提交安装时,更新可以访问之前版本的数据。

    使用此处描述的 Google Beta 测试功能: https://developer.android.com/distribute/best-practices/launch/test-tracks

    【讨论】:

    • 这是有道理的。现在出现了其他问题,但我会尽快试用 beta 测试功能,然后返回此处并标记为答案,如果它解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2020-07-09
    • 2021-09-16
    • 2018-06-19
    • 2019-08-03
    • 1970-01-01
    • 2022-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多