对SqlConnection使用context connection = true

时间:2016-07-04 13:14:36

标签: c# dapper

我有这个简化的课程:

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;
        }
}

此处连接字符串来自配置文件。我想在执行以下操作时使用配置文件中的凭据:

new SqlConnection("context connection=true")

我可以调整配置文件中的连接字符串,还是操纵IDbConnection的'connection'实例来实现这个目的?

2 个答案:

答案 0 :(得分:1)

我建议使用SqlConnectionStringBuilder

 // 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
}

当然,改变app.config只是一个偏好的问题。

答案 1 :(得分:0)

您可以使用SqlConnectionStringBuilder来更改已从配置文件中检索的连接字符串。这意味着您也可以只保留原始连接字符串。

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