How do I handle Database Connections with Dapper in .NET?

前端 未结 9 2077
闹比i
闹比i 2020-12-07 07:52

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

Most examples show the connection object being created in the

9条回答
  •  旧时难觅i
    2020-12-07 08:26

    It was asked about 4 years ago... but anyway, maybe the answer will be useful to someone here:

    I do it like this in all the projects. First, I create a base class which contains a few helper methods like this:

    public class BaseRepository
    {
        protected T QueryFirstOrDefault(string sql, object parameters = null)
        {
            using (var connection = CreateConnection())
            {
                return connection.QueryFirstOrDefault(sql, parameters);
            }
        }
    
        protected List Query(string sql, object parameters = null)
        {
            using (var connection = CreateConnection())
            {
                return connection.Query(sql, parameters).ToList();
            }
        }
    
        protected int Execute(string sql, object parameters = null)
        {
            using (var connection = CreateConnection())
            {
                return connection.Execute(sql, parameters);
            }
        }
    
        // Other Helpers...
    
        private IDbConnection CreateConnection()
        {
            var connection = new SqlConnection(...);
            // Properly initialize your connection here.
            return connection;
        }
    }
    

    And having such a base class I can easily create real repositories without any boilerplate code:

    public class AccountsRepository : BaseRepository
    {
        public Account GetById(int id)
        {
            return QueryFirstOrDefault("SELECT * FROM Accounts WHERE Id = @Id", new { id });
        }
    
        public List GetAll()
        {
            return Query("SELECT * FROM Accounts ORDER BY Name");
        }
    
        // Other methods...
    }
    

    So all the code related to Dapper, SqlConnection-s and other database access stuff is located in one place (BaseRepository). All real repositories are clean and simple 1-line methods.

    I hope it will help someone.

提交回复
热议问题