UWP using SQLite with Entity Framework Core

UWP is not directly compatible with .net core, could not add Microsoft.EntityFrameworkCore.Tools​ and execute migration commands in PMC, however, it implements .net standard 2.0 since version Windows 10 Fall Creators Update (10.0.16299), so you can create a related Class Library in .net standard 2.0 and refer it from your UWP project. Actually, a class library does not support Microsoft.EntityFrameworkCore.Tools too, because the migration command can only run with a .net framework or .net runtime. You can create a new Console app to implement the migrations. Full instructions:

Create blank solution in Visual Studio

Right click on the solution name in VS, add new project, choose UWP project to create, make sure you set the minimal version larger than Windows 10 Fall Creators Update (10.0.16299)

Add a new Class Library project, set its target framework to .net standard 2.0, install nuget package Microsoft.EntityFrameworkCore.Sqlite (choose the version that is compatible with .net standard 2.0, otherwise you could not refer it from your UWP project)​

Implement DbContext in Class Library project, sample codes:

public class AppDbContext : DbContext
{
    public AppDbContext()
    {
        var folder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        DbPath = Path.Combine(folder, "smtool.db");

        Database.Migrate();
    }

    protected override void OnConfiguring(DbContextOptionsBuilder builder)
        => builder.UseSqlite($"Data Source={DbPath}");

    public string DbPath { get; set; }

    // tables
    public DbSet<Setting> Settings { get; set; }
}

 

Create a Console app to add/apply/update/remove the migrations, set its target framework that is compatible with .net standard 2.0 as well, install nuget package Microsoft.EntityFrameworkCore.Tools​, refer the Class Library project in this Console app, set the Console app as Startup Project, then execute the migration, to add and update:

Add-Migration {migration_name} -project {class_library_project_name}
Update-Database -project {class_library_project_name}

Refer the Class Library project in your UWP project, now you can create new instance of your custom db context in your UWP project

创建时间:6/26/2022 1:56:08 AM 修改时间:6/26/2022 1:58:48 AM