如何在我的存储库模式代码中添加工作单元模式

本文关键字:模式 代码 工作 单元 添加 我的 存储 | 更新日期: 2023-09-27 18:28:59

我设计了一个小的存储库模式代码,但缺少工作单元。因此,我正在寻找指导,比如如何以最小的工作量将工作单元代码添加到我的存储库模式代码中。正在查找帮助和代码示例。这是我的完整代码。

基本存储库

 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);
        }
    }

如何在我的存储库模式代码中添加工作单元模式

您可以拥有一个包含存储库对象的工作单元类。

public class UnitOfWork : IUnitOfWork
{
    /// <summary>
    /// Database context.
    /// </summary>
    private readonly CoreDBContext context = new CoreDBContext();
    /// <summary>
    /// StudentRepository repository.
    /// </summary>
    public StudentRepository studentRepository 
    {
        get { return this.studentRepository ?? (this.studentRepository = new studentRepository (this.context)); }
    }
    public OtherRepository otherRepository
    {
        get { return this.otherRepository?? (this.otherRepository= new otherRepository(this.context)); }
    }
    /// <summary>
    /// Saves changes to database.
    /// </summary>
    public void Save()
    {
        this.context.SaveChanges();
    }
}

上面的存储库类包含数据库上下文、作为属性的存储库对象和保存方法。

在包含DAL层的引用后,您可以使用以下代码调用它

using (IUnitOfWork unitOfWork = new UnitOfWork())
        {
         StudentListViewModel SVm = new StudentListViewModel();
        SVm.SetUpParams(oSVm);
        SVm.Students =  unitOfWork.studentRepository.GetStudents(SVm.StartIndex, SVm.EndIndex, SVm.sort, oSVm.sortdir).ToList();
        }

可以更改存储库类以将中的DBContext对象作为构造函数对象。