Chris Becke
Chris Becke

Reputation: 36046

General way to switch between Sqlite or SqlServer in EF Core?

I want to be able to switch on the fly between using SQLite and SqlServer as a db provider for Entity Framework in an ASP.NET Core app.

The usual pattern to associate a DbContext with a Database Provider is via code in the ConfigureServices method:

        services.AddDbContext<FeedbackDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("Feedback")));

Each of the database providers for EF Core adds its own extension method as Use<Provider>.

It is surprising to me that I can't find a way to specify the database provider for a connection string in config

Upvotes: 7

Views: 7172

Answers (3)

Carlos Almeida
Carlos Almeida

Reputation: 33

When it comes to code changes only, you should modify context configuration. After installing Microsoft.EntityFrameworkCore.SqlServer NuGet package, you should be able to just change:

from:

services.AddDbContext<FeedbackDbContext>(
    options => options.UseSqlite(Configuration.GetConnectionString("Feedback")));

to:

services.AddDbContext<FeedbackDbContext>(
    options => options.UseSqlServer(Configuration.GetConnectionString("Feedback")));

Upvotes: 3

CodeClimber
CodeClimber

Reputation: 4191

Very nice article that shows how do have two contexts, one per DbProvider, and to be able to also generate different migrations:

https://jasonwatmore.com/post/2020/01/03/aspnet-core-ef-core-migrations-for-multiple-databases-sqlite-and-sql-server

Upvotes: 4

user1489673
user1489673

Reputation:

If you are on the same connection you can change the database name. I assume you will need to close, change then re-open. I've not tried this myself.

this.Database.GetDbConnection().ChangeDatabase("DB name");

Otherwise you can change the connection string to be used.

this.Database.GetDbConnection().ConnectionString = "new connection string";

I use a separate partial file to hold any of my own code to prevent overwriting by the system on any database rebuilds. You can add a method or property to change the current connection string. Again, you may need to close, change, and re-open

public partial class YourDbContext : DbContext
{
    void SetConnection(string s)

Upvotes: 1

Related Questions