【发布时间】:2015-06-23 21:15:22
【问题描述】:
这是我目前在我的一个存储库类中所做的:
private IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString);
public IEnumerable<Product> GetProducts(int categoryId = null, bool? active = null)
{
StringBuilder sql = new StringBuilder();
sql.AppendLine("SELECT * ");
sql.AppendLine("FROM Product ");
sql.AppendLine("WHERE @CategoryId IS NULL OR CategoryId = @CategoryId ");
sql.AppendLine(" AND @Active IS NULL OR Active = @Active");
return this.db.Query<Product>(sql.ToString(), new { CategoryId = categoryId, Active = active }).ToList();
}
我想做的一件事是将 IDbConnection 属性放在 BaseRepository 中,我的所有其他 repos 都继承自该 BaseRepository。我该怎么做才能确保我的数据库连接在我的每个数据访问功能(如上面的示例)中正确打开和关闭?这是我目前对 Entity Framework 所做的事情(每个函数都有一个 using 语句,但现在我将 DAL 切换为使用纯 Dapper:
using (var context = new MyAppContext())
{
var objList = (from p in context.Products
where (categoryId == null || p.CategoryId == categoryId) &&
(active == null || p.Active == active)
select p).ToList();
return objList;
}
我注意到在 Dapper examples 中,所有内容都像我所期望的那样包装在 using 语句中,但偶尔我会看到他们将其函数包装在以下 using 中:
using (var connection = Program.GetClosedConnection())
GetClosedConnection()返回一个新的SqlConnection,但是两者有什么区别呢?
public static SqlConnection GetOpenConnection(bool mars = false)
{
var cs = connectionString;
if (mars)
{
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(cs);
scsb.MultipleActiveResultSets = true;
cs = scsb.ConnectionString;
}
var connection = new SqlConnection(cs);
connection.Open();
return connection;
}
public static SqlConnection GetClosedConnection()
{
return new SqlConnection(connectionString);
}
【问题讨论】:
标签: c# sql sql-server database-connection dapper