Reputation: 36046
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
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
Reputation: 4191
Very nice article that shows how do have two contexts, one per DbProvider, and to be able to also generate different migrations:
Upvotes: 4
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