Home > OS >  How to create the first version of database file from code EF Core
How to create the first version of database file from code EF Core

Time:12-31

I am new to EF Core 3.1.22 using it with my .NET 4.6 desktop application. I am able to create the database and migrations using the package manager console, but my code doesn't generate the database file on its own at first run, when the database doesn't exist yet.

If I create the database using Update-Database from the package manager console, the file is created.

How can I update this code to generate the database file from code at first run and then apply database.migrate on that?

public class MyDbContextFactory : IDesignTimeDbContextFactory<MyDbContext>, IMyDbContextFactory
{       
    public MyDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
        optionsBuilder.UseSqlite($@"Data Source={DbConfiguration.GetDatabasePath()};", options =>
        {
            options.MigrationsAssembly(Assembly.GetExecutingAssembly().FullName);
        });

        return new MyDbContext(optionsBuilder.Options);
    }

    public MyDbContext CreateDbContext()
    {
        var dbcontext=  CreateDbContext(new[] { "" });
        dbcontext.Database.Migrate();
        return dbcontext;
    }
}

CodePudding user response:

Your connection string doesn't allow the database to be created, see the SQLite provider docs.

Either change it to Mode=ReadWriteCreate or remove it entirely as it's the default setting.

  • Related