0

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.

5
  • Modify the connection string appropriately and call EnsureCreated? Commented Apr 18, 2022 at 7:27
  • Context.Database.EnsureCreated(); will create a database if not created Commented Apr 18, 2022 at 7:48
  • yeah I know but it gives this error: You need to call SQLitePCL.raw.SetProvider(). If you are using a bundle package, this is done by calling SQLitePCL.Batteries.Init().' Commented Apr 18, 2022 at 7:56
  • Micrsofot docs: Don't call EnsureCreated() before Migrate(). EnsureCreated() bypasses Migrations to create the schema, which causes Migrate() to fail Commented Apr 18, 2022 at 13:10
  • @OkanKaradag so what should I do in my solution? Commented Apr 18, 2022 at 16:18

1 Answer 1

1

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());
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.