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

c# entity-framework-core production-environment sqlite xamarin.forms

Question

First I run the following setup

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

And everything works fine. The .db file is generated properly and queries are executed on the database. Then I prepared the application for production and I changed the DEBUG to RELEASE compiled, and packed into an apk. As installed on the device the application always crashes when calling either Database.Migrate() or Database.EnsureCreated()

The scenario is the same on every application I tried. App runs properly in emulator and on the device being in DEBUG mode. App crashes on every Android device when creating the database.

This is the instantiation of the DbContext

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

This is how the constructor is called

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));
}

This is how I retrieve the filepath on Android.

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

When looking on the Android Device Monitor a very long error is displayed The beginning is Error message part 1 somewhere later there is the EnsureCreated method listed Error message part 2

The Question: Why is this happening and how to make the application runnable on production?

1
3
8/20/2019 11:50:59 AM

Accepted Answer

Do you have linking enabled in your release build configuration? According to this 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: Xamarin iOS Linker Issue and here: https://docs.microsoft.com/en-us/xamarin/android/deploy-test/linker#linkskip.

I can't personally test at the moment but I think putting [assembly: Preserve (typeof (System.Linq.Queryable), AllMembers = true)] (or whatever assembly might be causing it) in your App.xaml.cs should do it.

1
8/20/2019 12:45:39 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow