Stuffi
Stuffi

Reputation: 11

Migrate SQLite-database from another assembly using EF-Core

I am developing a C# project using EF Core. The solution contains two projects:

• Project A: a WinForms project to run the application

• Project B: a project to manage a SQLite-database

Project B contains the DbContext, migrations an so on.

DbContext-Class:

public class ContextTest : DbContext 
{
    public DbSet<LogTest> LogTests { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options) 
    {
       string sqlitePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log.db");
       options.UseSqlite($"Data Source={sqlitePath}");
    }
} 

Class for executing the migrations:

public class DbMigrator 
{
    public static void ExecuteMigrations() {
        using (var context = new ContextTest()) 
        {
            context.Database.Migrate();
        }
    }
}

If I configure project B as the startup project, I can do the migrations without any problems. But if project A is set as the start project, I get a System.NullReferenceException as soon as context.Database.Migrate(); is called.

I have tried already to set the MigrationsAssembly:

options.UseSqlite($"Data Source={sqlitePath}", 
               o => o.MigrationsAssembly(typeof(ContextTest).Assembly.GetName().Name));

It didn't help. I have to call up migrations from Project A. Maybe someone has an idea?

Upvotes: 0

Views: 912

Answers (1)

Andrew McFall III
Andrew McFall III

Reputation: 83

My first question is this: "What is the null reference referring to?" The Context or the Database? one of the very first things that happens in a db migration (Code First) is that the target is effectively dropped. With SQL Server, that means that the target database is deactivated and placed in "single-user mode" where only the db server admin can get to it. With SQLite, I believe it is de-referenced at the machine level. Both of these operations are done so that the database engine can actually run the "Create Database" sequence under the hood. Thank you Code-First Development.

If the purpose of the application is to handle business logic, and the purpose of the database project is to manage the database, managing the db from the business side of the house with EF Core only makes sense in VERY specific scenarios.

The problem is that (as of this posting) EF Core (any version) is not designed to much of anything from the database first. In your case a database migration from the application side could mean multiple schema updates, new tables being created because of newly discovered domain entities or other hidden dependencies.

If all you're doing is moving from say "Dev" to "Test", or from "Test" to "Prod", the DAL wouldn't necessarily have to know about any of that, and db migrations can actually be left alone (with SQLite anyway), because the schema isn't going to change.

Upvotes: 2

Related Questions