2

I have this simplified class:

public abstract class BaseDaService
{
    private readonly string _connectionString;

    protected BaseDaService(string connectionString)
    {
        _connectionString = connectionString;
        }

        protected IDbConnection OpenConnection()
    {
        IDbConnection connection = new SqlConnection(_connectionString);
        connection.Open();
        return connection;
        }
}

Here the connection string comes from a config file. I would like to use credentials from my config files whilst doing:

new SqlConnection("context connection=true")

Can I adapt the connection string in the config file or manipulate the 'connection' instance of IDbConnection to achieve this?

2
  • Would this work? SqlConnectionStringBuilder sqlb = new SqlConnectionStringBuilder(_connectionString); sqlb.ContextConnection = true;
    – pijemcolu
    Jul 4, 2016 at 13:17
  • Thanks, was looking for this. Will give it a go.
    – cs0815
    Jul 4, 2016 at 13:20

2 Answers 2

1

I suggest to use the SqlConnectionStringBuilder class

 // With a default parameter set to false you can still use
 // the same code as before and change only the spots where
 // the context is required
 protected IDbConnection OpenConnection(bool useContext = false)
 {

    string newConString = _connectionString;
    if(useContext)
    {
        SqlConnectionStringBuilder scs = new SqlConnectionStringBuilder(_connectionString);
        scs.ContextConnection = true;
        newConString = scs.ToString();
    }
    IDbConnection connection = new SqlConnection(newConString);
    connection.Open();
    return connection
}

Of course changing the app.config is just a matter of preference.

0

You can use SqlConnectionStringBuilder in order to change the connection string which you have already retrieved from the config file. That means you could as well keep your original connection string readonly.

SqlConnectionStringBuilder sqlb = new SlConnectionStringBuilder(_connectionString); 
sqlb.ContextConnection = true;
string modifiedConnString = sqlb.ToString();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.