How to switch between sqlserver and postgresql using entity framework by parameters

asp.net-core entity-framework-core postgresql sql-server

Question

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.

1
1
1/24/2019 8:04:32 AM

Popular Answer

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"));
    }
});
0
1/25/2019 7:07:10 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow