在ADO.Net存储库模式中处理异常的最佳方式

本文关键字:异常 处理 最佳 方式 模式 ADO Net 存储 | 更新日期: 2023-09-27 18:28:52

我已经为ado.net设计了小型存储库模式。现在我无法以正确的方式处理异常。如果发生任何错误,我想将其推送到调用环境。若并没有发生错误,那个么结果集将被推送到调用环境。

我有一个名为AdoRepository的存储库,它扩展了其他存储库类,如employee等。我们从mvc控制器调用employee repository function。所以我想把错误从employee repository推送到mvc控制器,如果在数据提取过程中发生任何错误,如果没有发生错误,那么数据将被发送到mvc控制器。这是我的完整代码。请看一看并分享最佳设计的想法。如果可能,请在此处粘贴已更正的代码。

基本存储库

 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)
        {
            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);
                }
            }
            finally
            {
                // Always call Close when done reading.
                reader.Close();
                _connection.Close();
                _connection.Dispose();
            }
            return list;
        }
    }
StudentRepository which extend base AdoRepository
-----------------------------------------------
public class StudentRepository : AdoRepository<Student>
    {
        public int DataCounter { get; set; }
        public bool hasError { get; set; }
        public string ErrorMessage { get; set; }
        public StudentRepository(string connectionString)
            : base(connectionString)
        {
        }
        public IEnumerable<Student> GetAll()
        {
            // DBAs across the country are having strokes 
            //  over this next command!
            using (var command = new SqlCommand("SELECT ID, FirstName,LastName,IsActive,StateName,CityName FROM vwListStudents"))
            {
                return GetRecords(command);
            }
        }
        public Student GetById(string id)
        {
            // PARAMETERIZED QUERIES!
            using (var command = new SqlCommand("SELECT ID, FirstName,LastName,IsActive,StateName,CityName FROM vwListStudents WHERE Id = @id"))
            {
                command.Parameters.Add(new ObjectParameter("id", id));
                return GetRecord(command);
            }
        }
        public IEnumerable<Student> GetStudents(int StartIndex, int EndIndex, string sortCol, string sortOrder)
        {
            string strSQL = "SELECT * FROM vwListStudents WHERE ID >=" + StartIndex + " AND ID <=" + EndIndex;
            strSQL += " ORDER BY " + sortCol + " " + sortOrder;
            strSQL += ";SELECT COUNT(*) AS Count FROM vwListStudents";
            var command = new SqlCommand(strSQL);
            return GetRecords(command);
        }
        public override Student PopulateRecord(SqlDataReader reader)
        {
            return new Student
            {
                ID = Convert.ToInt32(reader["ID"].ToString()),
                FirstName = reader["FirstName"].ToString(),
                LastName = reader["LastName"].ToString(),
                IsActive = Convert.ToBoolean(reader["IsActive"]),
                StateID = Convert.ToInt32(reader["StateID"].ToString()),
                StateName = reader["StateName"].ToString(),
                CityID = Convert.ToInt32(reader["CityID"].ToString()),
                CityName = reader["CityName"].ToString()
            };
        }
        public override void GetDataCount(int count)
        {
            DataCounter = count;
        }
        public override void Status(bool IsError, string strErrMsg)
        {
            hasError = IsError;
            ErrorMessage = strErrMsg;
        }
}

从mvc控制器调用StudentRepository,如下所示

 public class StudentController : Controller
    {
        private StudentRepository _data;
        public StudentController()
        {
            _data = new StudentRepository(System.Configuration.ConfigurationManager.ConnectionStrings["StudentDBContext"].ConnectionString);
        }
        // GET: Stuent
        public ActionResult List(StudentListViewModel oSVm)
        {
            StudentListViewModel SVm = new StudentListViewModel();
            SVm.SetUpParams(oSVm);
            SVm.Students = _data.GetStudents(SVm.StartIndex, SVm.EndIndex, SVm.sort, oSVm.sortdir).ToList();
            SVm.RowCount = _data.DataCounter;
            return View("ListStudents",SVm);
        }
    }

在ADO.Net存储库模式中处理异常的最佳方式

我不明白这一点:

        catch (Exception ex)
        {
            Status(true, ex.Message);
        }

简单地说,不要抓住异常,让它出现在调用者身上,根据你的说法,调用者会知道如何处理它。不需要回调。

将检索到的数据存储在实例状态中似乎是一种糟糕的做法。相反,返回一个包含该数据的对象。这导致了一个更直接的API,并且具有更少的可变状态。


        finally
        {
            reader.Close();
            _connection.Close();
            _connection.Dispose();
        }

有一种更好的方法:在using语句中封装资源。特别是与迷信的两面派模式分道扬镳。

让调用者处理异常,确保您记录了一条像样的错误消息(显示所有相关字段)。Status类会惹恼那些根本不支持的人,因为它吞噬了堆栈跟踪,而对导致错误的数据只字未提。DB异常通常是由格式错误的数据引起的,因此在出现问题时记录这些数据非常重要。

顺便说一句,PopulateRecord和GetDataCount方法应该是抽象的,因为基本版本什么都不做。另一个开发人员可能很容易认为他们不需要实现这些方法,并且会留下一个包含无用的PopulateRecord和GetDataCount方法的类。