开发者

ASP.NET MVC Manage SQLConnection with Dapper

I am giving the new Dapper Micro ORM released by Stack Overflow/Sam Saffron a quick go using MVC. I'm wondering what is the simplest way to manage a SQLConnection object inside my controller? I am doing something simple like this just to spin through some data and test out Dapper, but is it idea to be opening/closing the connection like so?

public class HomeController : Controller
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ajh"].Connection开发者_运维知识库String);

    public HomeController()
    {
    }

    public ActionResult Index()
    {
        // get me all comments
        conn.Open();
        var comments = conn.ExecuteMapperQuery<Comment>("select * from Comment");
        conn.Close();

        return View(comments);
    }
}


Just create, open and close the connection as locally as possible:

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);
    }
}

Although it's best practice to avoid direct data-access in your controllers. Bury your data-access methods inside a CommentsService class or similar and call that from your controller.


I've never used it, but of var comments is deferred in its execution, then you'll have a problem and will have to use something like .ToList to fully enumerate the results before closing the connection. Otherwise, if .ExecuteMapperQuery fully enumerates the results before returning them you will be fine

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜