Search code examples
c#sqliteentity-framework-coreef-code-first

Create Database on Runtime - Entity FrameWork Code-First


I have a project which saves its output results into an SQLite database. in every run, the user should select the saving location which the program will create a database there and will save the result inside. so the database's name and location are dynamic.

How can I manage such a thing using entity framework core code first? I have create the models and the DbContext class, but I do not know how to create the database and tables on runtime and so on.


Solution

  • I have found the solution, I should use raw.SetProvider(new SQLite3Provider_e_sqlite3()); in OnConfiguring:

    public MyDataContext(string path, bool create = true)
    {
        FilePath = path;
        if (create)
        {
            Database.EnsureDeleted();
            Database.EnsureCreated();
        }
    }
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionbuilder)
    {
        optionbuilder.UseSqlite($"Data Source={FilePath}");
        raw.SetProvider(new SQLite3Provider_e_sqlite3());
    }