I have a simple WPF/EF Core 2.2.4 application that uses postgres.
I'm analyzing the possible strategies to migrate it on SQL Server.
In non ORM applications, it's quite common to limit the database-specific reference to the connection string togheter with providing a way to dynamically load the database driver (thinking of JDBC model). In that model you have to address the problem of writing SQL that works cross databases.
Here the problem of SQL writing, actually the major one, is solved right from the start. So I find it quite paradoxical that we sort of reintroduce database dependency in the form of helper methods.
My first question is about the DbContext. The OnConfiguring receives a DbContextOptionsBuilder that is used to pass Connection string.
But in order to pass the connection string you use a database-specific method that is provided as an extension method by the database provider.
That is the optionsBuilder.UseNpgsql(connstr) in the following example.
How should I address this in a database-independend application?
class MyDbContext: DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string connstr =
ConfigurationManager
.ConnectionStrings["MYAPP_PROD"].ConnectionString;
optionsBuilder.UseNpgsql(connstr);
}
}
The second question is: how can I load the entire database package in a dynamic way, so that I can manage to configure it instead of harcoding it? Actually I use NuGet to get the package:
Npgsql.EntityFrameworkCore.PostgreSQL
Say that I want to use:
Microsoft.EntityFrameworkCore.SqlServer
How can this be done?
Use the strategy pattern to register the relevant database provider based on external configuration.