Mou Mou - 1 month ago 6
C# Question

C#: Return dynamic sql connection based on T type by generic usage

suppose i am working with many sql connection object. some connect my local db, some connect my remote db etc

public static T GetGenericConnection<T>()
{

}


so i want to call a function like
GetGenericConnection<DBLocal>() or GetGenericConnection<DBRemote>()
then
GetGenericConnection
will return sql connection object as T based on pass value. pass value means few class name like
DBLocal or DBRemote


or i will call function like
GetGenericConnection<ConnectionType.DBLocal>() or GetGenericConnection<ConnectionType.DBRemote>()
.

ConnectionType.DBLocal
is enum type.

GetGenericConnection
function will return
DBLocal or DBRemote
instance as type T based on pass value.

please show me how to achieve this with sample code. thanks

UPDATE



public static T GetGenericConnection<T>(ConnectionType ConnectionFor)
{
if (ConnectionFor == ConnectionType.LocalSQLConnection)
return (T)Convert.ChangeType((new BBASQLLocalConnection()).Connection, typeof(T));
else if (ConnectionFor == ConnectionType.ORCSWEBSQLConnection)
return (T)Convert.ChangeType((new BBAORCSSQLConnection()).Connection, typeof(T));
else if (ConnectionFor == ConnectionType.ReportConnection)
return (T)Convert.ChangeType((new BBASQLReportConnection()).Connection, typeof(T));
else
return (T)Convert.ChangeType((new BBASAGEConnection()).Connection, typeof(T));
}


some kind of problem occur when i call function like this way

SqlConnection conn1 = (SqlConnection) ConnectionManager.Factory.BBADBConnectionFactory.GetGenericConnection<BBASQLLocalConnection>(ConnectionType.LocalSQLConnection);


Error message was


Cannot convert type 'ConnectionManager.BBASQLLocalConnection' to
'System.Data.SqlClient.SqlConnection

Answer

You don't need a generic type parameter for this. Just a regular argument will do:

public static IDbConnection GetDatabaseConnection(ConnectionType db) 
{

    switch (db)
    {
        case ConnectionType.DBLocal:
            return new SqlConnection("dblocal connection string here");
            break;
        case ConnectionType.DBRemote:
            return new SqlConnection("db remote connection string here");
            break;
        default:
            throw new InvalidArgumentException("Unrecognized DB Type");
            break;
    }    
}

Okay, based on your update I see more of what your problem is; you have wrapper objects for your connection types. What I'm suggesting here is still the correct approach. What changes with the question edit is that you also need to make sure your special connection wrapper types all implement a common interface.