如何重构我的存储库设计代码c#

时间:2016-02-11 10:46:56

标签: c# ado.net

首先看我的代码

public abstract class AdoRepository<T> where T : class
    {
        private SqlConnection _connection;
        public virtual void Status(bool IsError, string strErrMsg)
        {

        }

        public AdoRepository(string connectionString)
        {
            _connection = new SqlConnection(connectionString);
        }

        public virtual T PopulateRecord(SqlDataReader reader)
        {
            return null;
        }

        public virtual void GetDataCount(int count)
        {

        }

        protected IEnumerable<T> GetRecords(SqlCommand command)
        {
            var reader = (SqlDataReader) null;
            var list = new List<T>();
            try
            {
                command.Connection = _connection;
                _connection.Open();
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    list.Add(PopulateRecord(reader));
                }

                reader.NextResult();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        GetDataCount(Convert.ToInt32(reader["Count"].ToString()));
                    }
                }
                Status(false, "");
            }
            catch (Exception ex)
            {
                Status(true, ex.Message);
            }
            finally
            {
                // Always call Close when done reading.
                reader.Close();
                _connection.Close();
                _connection.Dispose();
            }

            return list;
        }

        protected T GetRecord(SqlCommand command)
        {
            var reader = (SqlDataReader)null;
            T record = null;

            try
            {
                command.Connection = _connection;
                _connection.Open();

                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    record = PopulateRecord(reader);
                    Status(false, "");
                    break;
                }
            }
            catch (Exception ex)
            {
                Status(true, ex.Message);
            }
            finally
            {
                reader.Close();
                _connection.Close();
                _connection.Dispose();
            }
            return record;
        }

        protected IEnumerable<T> ExecuteStoredProc(SqlCommand command, string CountColName="TotalCount")
        {
            var reader = (SqlDataReader)null;
            var list = new List<T>();

            try
            {
                command.Connection = _connection;
                command.CommandType = CommandType.StoredProcedure;
                _connection.Open();
                reader = command.ExecuteReader();

                while (reader.Read())
                {
                    var record = PopulateRecord(reader);
                    if (record != null) list.Add(record);
                }

                reader.NextResult();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        GetDataCount(Convert.ToInt32(reader[CountColName].ToString()));
                    }
                }

            }
            finally
            {
                // Always call Close when done reading.
                reader.Close();
                _connection.Close();
                _connection.Dispose();
            }
            return list;
        }
    }

public class CityRepository : AdoRepository<City>
    {
        public int DataCounter { get; set; }
        public bool hasError { get; set; }
        public string ErrorMessage { get; set; }

        public CityRepository(string connectionString)
            : base(connectionString)
        {
        }

        public IEnumerable<City> GetAll()
        {
            // DBAs across the country are having strokes 
            //  over this next command!
            using (var command = new SqlCommand("SELECT ID, CityName,StateID FROM City"))
            {
                return GetRecords(command);
            }
        }

        public City GetById(string id)
        {
            // PARAMETERIZED QUERIES!
            using (var command = new SqlCommand("SELECT ID, CityName FROM City WHERE Id = @id"))
            {
                command.Parameters.Add(new ObjectParameter("id", id));
                return GetRecord(command);
            }
        }

        public IEnumerable<City> GetCityByStateId(int stateid)
        {
            // PARAMETERIZED QUERIES!
            using (var command = new SqlCommand("SELECT ID, CityName,StateId FROM City WHERE StateId = @stateid"))
            {
                command.Parameters.Add("StateId", DbType.Int32).Value = stateid;
                return GetRecords(command);
            }
        }

        public override City PopulateRecord(SqlDataReader reader)
        {
            return new City
            {
                ID = Convert.ToInt32(reader["ID"].ToString()),
                Name = reader["CityName"].ToString(),
                StateID = Convert.ToInt32(reader["StateId"].ToString())
            };
        }

        public override void Status(bool IsError, string strErrMsg)
        {
            hasError = IsError;
            ErrorMessage = strErrMsg;
        }

}

请参阅以下我想要构建的代码

protected IEnumerable<T> ExecuteStoredProc(SqlCommand command, string CountColName="TotalCount")
{
    var reader = (SqlDataReader)null;
    var list = new List<T>();

    try
    {
        command.Connection = _connection;
        command.CommandType = CommandType.StoredProcedure;
        _connection.Open();
        reader = command.ExecuteReader();

        while (reader.Read())
        {
            var record = PopulateRecord(reader);
            if (record != null) list.Add(record);
        }

        reader.NextResult();
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                GetDataCount(Convert.ToInt32(reader[CountColName].ToString()));
            }
        }

    }
    finally
    {
        // Always call Close when done reading.
        reader.Close();
        _connection.Close();
        _connection.Dispose();
    }
    return list;
}

如果存储过程返回更多结果集如3或4或者可能更多如何设计 ExecuteStoredProc()函数体或者我是否需要重载它但是如果我会超载 ExecuteStoredProc()函数然后没有参数我需要增加可能是不必要的。所以我正在寻找 ExecuteStoredProc()函数的最佳代码设计指南,结果有多少 resultset 我的存储过程返回代码可以很好地处理它。

寻找最佳设计指南。感谢

0 个答案:

没有答案