ASP.NET MVC使用Dapper管理SQLConnection

ahe*_*ick 7 c# asp.net-mvc orm sqlconnection

我正在使用Stack Overflow/Sam Saffron发布的新Dapper Micro ORM快速使用MVC.我想知道在我的控制器中管理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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Luk*_*keH 9

只需在本地创建,打开和关闭连接:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

尽管最好避免在控制器中直接访问数据.将您的数据访问方法隐藏在CommentsService类或类似内容中,并从控制器中调用它.

  • @aherrick:很公平,我可能会这样做.如果代码真的很简单,那么添加额外的图层和抽象通常会让事情变得更糟,而不是更好! (2认同)