0
I wrote a C# method to make a "switch" between different database types in my application. Where the problem is that each database type makes use of a different library (SQL => Sqlconnection and Postgresql => Npgsql)
For this, I wrote the following method:
public dynamic GetConnection()
{
bool isProduction = Convert.ToBoolean(_configuration.GetSection("Databases:0").GetSection("isProduction").Value);
string dbType = _configuration.GetSection("Databases:0").GetSection("Type").Value;
if (dbType == "MSSQL" || dbType == "sql")
{
switch (isProduction)
{
case true:
return new SqlConnection(_configuration.GetSection("Databases:0").GetSection("productionConnectionString").Value);
case false:
return new SqlConnection(_configuration.GetSection("Databases:0").GetSection("developmentConnectionString").Value);
}
}
else if (dbType == "PostgreSQL" || dbType == "Postgre")
{
switch (isProduction)
{
case true:
return new NpgsqlConnection(_configuration.GetSection("Databases:0").GetSection("productionConnectionString").Value);
case false:
return new NpgsqlConnection(_configuration.GetSection("Databases:0").GetSection("developmentConnectionString").Value);
}
}
return new Exception("Database type not found.");
}
Where in each situation, has its return as would be in my repository using Dapper. However, consuming this new method of mine, the compiler cannot identify that I am using Dapper and gets lost, giving the following error:
'System.Data.SqlClient.SqlConnection' does not contain a definition for 'Query'
Below is the code that makes the consumption of this new method:
public IEnumerable<TaskModel> GetAll()
{
IEnumerable<TaskModel> result;
string query = "SELECT * FROM Task";
// using (var con = new SqlConnection(_configuration.GetSection("Databases:0").GetSection("productionConnectionString").Value))
using (var con = GetConnection())
{
result = con.Query<TaskModel>(query);
}
return result;
}
are different Connections, do not implement neither the same interfaces, can not use both of this meneira.write a class that "decide" which database method to use (can be a
factory
, etc), make the query and return, so you will have a single query point– Ricardo Pontual