How to break the database access class of a Repository

ぃ、小莉子 提交于 2021-01-07 02:52:19

问题


I have the following tightly coupled database access class (repository), that is hard to unit test:

class EmployeesRepository : IEmployeeRepository ...

public IEnumerable<Employee> GetAllEmployees()
{
    List<Employee> list = new List<Employee>();

    try
    {           
        string connectionString = _secureConfig.Value.MyDbSetting;
        
        string sql = "select id, firstname, lastname, entrydate, email from empoyees";
        using SqlConnection connection = new SqlConnection(connectionString);
        using SqlCommand command = new SqlCommand(sql, connection);
        connection.Open();

        using SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            list.Add(new Employee
            {
                Id = reader.GetString(0),
                FirstName = reader.GetString(1),
                LastName = reader.GetString(2),
                EntryDate = reader.GetDateTime(3),
                Email = (reader.IsDBNull(4) ? null : reader.GetString(4))
            });
        }
    }
    catch (Exception ex)
    {
        _log.LogError(ex, "An error is caught when getting all employees");
    }
    return list;
}

sometimes the same code uses command.ExecuteNonQuery(), there are also sometimes connection.BeginTransaction()...

My question is what is the pattern should be used to decouple this class into logical units, in order to facilitate integration testing.

来源:https://stackoverflow.com/questions/65599782/how-to-break-the-database-access-class-of-a-repository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!