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

标签 c# asp.net-mvc orm sqlconnection

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

相关文章:

c# - 使用 C# 编辑 HTML

c# - 从主 ASP .NET 应用程序中分离出 Web API Controller

asp.net-mvc - ASP.NET MVC : how to catch a 404 error?

php - 哪个 PHP ORM 最适合 Zend Framework?

java - jackson JSON 和 Hibernate JPA 问题的无限递归

c# - WPF WebBrowser (3.5 SP1) Always on top - 在 WPF 中显示 HTML 的其他建议

c# - 在基于 Web 的架构上使用 POCO、DTO 和 ViewModel

c# - 传递对象的关联数组

php - Symfony 表单错误 : "Expected argument of type "Doctrine\ORM\QueryBuilder", "Doctrine\ORM\Query"给出”

c# - 在 WPF 中,如何在设计 View 中将样式应用于 UserControl?