我正在使用 MVC 快速介绍 Stack Overflow/Sam Saffron 发布的新 Dapper Micro ORM。我想知道在我的 Controller 中管理 SQLConnection 对象的最简单方法是什么?我正在做一些像这样简单的事情,只是为了浏览一些数据并测试 Dapper,但是像这样打开/关闭连接是个主意吗?
public class HomeController : Controller
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ajh"].ConnectionString);
public HomeController()
{
}
public ActionResult Index()
{
// get me all comments
conn.Open();
var comments = conn.ExecuteMapperQuery<Comment>("select * from Comment");
conn.Close();
return View(comments);
}
}
最佳答案
尽可能在本地创建、打开和关闭连接:
public class HomeController : Controller
{
public HomeController()
{
}
public ActionResult Index()
{
List<Comment> comments;
using (var conn = new SqlConnection(/* ... */))
{
conn.Open();
comments = conn.ExecuteMapperQuery<Comment>("select * from Comment");
}
return View(comments);
}
}
尽管最好避免在 Controller 中直接访问数据。将您的数据访问方法埋入 CommentsService
类或类似的类中,并从您的 Controller 中调用它。
关于c# - ASP.NET MVC 使用 Dapper 管理 SQLConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5717166/