在.NET中如何处理数据库连接与小巧玲珑的? [英] How do I handle Database Connections with Dapper in .NET?

查看:167
本文介绍了在.NET中如何处理数据库连接与小巧玲珑的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩短小精悍,但我不知道来处理数据库连接的最佳方式。

I've been playing with Dapper, but I'm not sure of the best way to handle the database connection.

大多数示例显示连接对象正在在示例类创建,或者甚至在每个方法。但感觉不对的我引用一个连接字符串中的每一个CLSS,即使它从web.config拉动。

Most examples show the connection object being created in the example class, or even in each method. But it feels wrong to me to reference a connection string in every clss, even if it's pulling from the web.config.

我的经验与使用 DbDataContext 的DbContext 使用LINQ to SQL或实体框架,所以这是新的给我。

My experience has been with using a DbDataContext or DbContext with Linq to SQL or Entity Framework, so this is new to me.

如何构建我的Web应用程序使用精致小巧的我的数据访问策略时?

How do I structure my web apps when using Dapper as my Data Access strategy?

推荐答案

我创建与检索从配置的连接字符串的属性扩展方法。这让来电者不必了解连接任何东西,无论是打开或关闭,等等。这种方法确实限制你一点,因为你隐藏了一些小巧玲珑的功能,但在我们的相当简单的应用程序,它为我们工作得很好,如果我们需要更多的功能,从小巧精致的,我们可以随时添加,它公开它一个新的扩展方法。

I created extension methods with a property that retrieves the connection string from configuration. This lets the callers not have to know anything about the connection, whether it's open or closed, etc. This method does limit you a bit since you're hiding some of the Dapper functionality, but in our fairly simple app it's worked fine for us, and if we needed more functionality from Dapper we could always add a new extension method that exposes it.

internal static string ConnectionString = new Configuration().ConnectionString;

    internal static IEnumerable<T> Query<T>(string sql, object param = null)
    {
        using (SqlConnection conn = new SqlConnection(ConnectionString))
        {
            conn.Open();
            return conn.Query<T>(sql, param);
        }
    }

    internal static int Execute(string sql, object param = null)
    {
        using (SqlConnection conn = new SqlConnection(ConnectionString))
        {
            conn.Open();
            return conn.Execute(sql, param);
        }
    }

这篇关于在.NET中如何处理数据库连接与小巧玲珑的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆