Xamarin Forms +Entity Framework Core + SQLite - 在生产中断应用程序时调用迁移

Xamarin Forms +Entity Framework Core + SQLite - Calling migration on production breaks application

首先我运行下面的设置

Xamarin Forms - Entity Framework Core 2.2 - SQLite - Android - DEBUG

一切正常。正确生成 .db 文件并在数据库上执行查询。 然后我准备生产应用程序,我将 DEBUG 更改为 RELEASE 编译,并打包到一个 apk 中。安装在设备上的应用程序在调用 Database.Migrate()Database.EnsureCreated()

时总是崩溃

我尝试过的每个应用程序的场景都是一样的。应用程序 运行s 在模拟器和处于 DEBUG 模式的设备上正常运行。创建数据库时,应用程序在每个 Android 设备上崩溃。

这是DbContext

的实例化
public ItemContext(DbContextOptions<ItemContext> options)
    : base(options)
{
    //Database.Migrate();
    Database.EnsureCreated();
}

构造函数是这样调用的

public void Load()
{
    string databasePath = DependencyService.Get<ILocalFileStorageService>().GetDatabaseFilePath("ItemSQLite.db");

    string connectionString = $"Filename={databasePath}";
    DbContextOptions<ItemContext> options = new DbContextOptionsBuilder<ItemContext>()
            .UseSqlite(connectionString)
            .Options;

    dataService = new DataService(new ItemContext(options));
}

这就是我在 Android 上检索文件路径的方式。

public string GetDatabaseFilePath(string fileName)
{
    string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
    return Path.Combine(path, fileName);
}

查看 Android 设备监视器时显示一个很长的错误 开头是 稍后某处列出了 EnsureCreated 方法

问题:为什么会发生这种情况以及如何使应用程序 运行 能够投入生产?

您的发布版本配置中是否启用了链接?据此https://github.com/aspnet/EntityFrameworkCore/issues/10963 the compiler requires hints to not link assemblies accessed through reflection internally in EF Core. You can try switching to "Link sdk assemblies only" to see if that fixes the issue. If it does then you will need to identify the assemblies and mark them to be preserved. There's some more info on that here: and here: https://docs.microsoft.com/en-us/xamarin/android/deploy-test/linker#linkskip.

我目前无法亲自测试,但我认为将 [assembly: Preserve (typeof (System.Linq.Queryable), AllMembers = true)](或任何可能导致它的程序集)放入您的 App.xaml.cs 应该可以。