这是我当前在我的存储库类之一中所做的事情:
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 中。我该如何确保我的数据库连接在每个数据访问函数(如上面的示例)中正确打开和关闭?以下是我目前使用 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);
}
最佳答案
我一直都是这么做的:
SqlConnection dbConnection;
using (dbConnection = new SqlConnection(connectionString))
{
/*
Whatever Dapper stuff you want to do. Dapper will open the
connection and the using will tear it down.
*/
}
至于你问题的第二部分,GetClosedConnection
只需实例化 SqlConnection
对象,而 GetOpenConnection
实例化并打开 SqlConnection
目的。您(或 Dapper)必须手动调用 Open()
在 GetClosedConnection
返回的对象上.
关于c# - 确保每次使用 Dapper 访问数据库时数据库连接打开和关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31013666/