gpt4 book ai didi

c# - ASP.NET MVC 使用 Dapper 管理 SQLConnection

转载 作者:太空狗 更新时间:2023-10-29 20:14:46 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com