Reputation: 127
I'm developing a small project, and requirements must be allow user switch database between sqlserver and postgresql or more.
I think, i need a parameter to switch database in json configuration file as:
"DatabaseType": "MsSQL"
My question is how to i implement that with entity framework core?
What can i do with DbContext and switch them?
Sorry if my English not good.
Upvotes: 1
Views: 1899
Reputation: 30016
For swithing the database with the same DbContext, you need to make sure your database map the DbContext Structor.
For achieve this, you could try define the parameter like
{
"DatabaseType": "MsSQL1",
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-TestIdentity2_2-C9C6DF1A-1A9A-497A-871E-618806FC959F;Trusted_Connection=True;MultipleActiveResultSets=true",
"MySqlConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-MySql-2C4FD13B-62DA-4B5D-8C8C-8F9C42CD3A67;Trusted_Connection=True;MultipleActiveResultSets=true"
},
}
Configure in Startup.cs
services.AddDbContext<ApplicationDbContext>(options =>
{
var dbType = Configuration["DatabaseType"];
if (dbType == "MsSQL")
{
//change this to your postgresql config
options.UseSqlServer(
Configuration.GetConnectionString("MySqlConnection"));
}
else
{
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"));
}
});
Upvotes: 1