jeudi 7 avril 2016

EF7 throws exception when querying SQLite database on UWP app

I'm writing a UWP version of a Windows Phone 8.1 app of mine. This app uses a read-only SQLite database and I'm trying to use Entity Framework 7 on the UWP app to access it.

I can read the database just fine in the app's initial page. However, once I tap one of the rows to navigate to that row's detail page (where I fetch some child records), I get an exception saying there are no database providers configured, even though the code to access the database is the same as in the page that's working. The weirder part is that if I step through the code using the debugger, it works.

I'm also using Template10 on my app, but it does not make a difference whether I put the DB access code in a Template10 ViewModel or straight in the code-behind for the view.

This is the OnConfiguring method for my DbContext class:

    protected async override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var assetsFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");
        optionsBuilder.UseSqlite($"Filename={Path.Combine(assetsFolder.Path, "joinbus.db")}");
    }

This is how I access the database on the app's initial page (which always works):

    public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> state)
    {
        using (var db = new JoinbusContext())
        {
            Lines = await db.Lines.ToListAsync();
        }
    }

This is how I access the database on the detail page (which only works when debugging):

    public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> state)
    {
        var line = parameter as Line;
        using (var db = new JoinbusContext())
        {
            var origins = await db.LineOrigins.Where(lo => lo.Line.Id == line.Id)
                .Include(lo => lo.Origin).ToListAsync();
            LineOrigins = origins;
        }
    }

The exception thrown is System.InvalidOperationException with the message "No database providers are configured. Configure a database provider by overriding OnConfiguring in your DbContext class or in the AddDbContext method when setting up services."

Aucun commentaire:

Enregistrer un commentaire