使用Entityframework,Genericrepository,UnitOfWork和storedprocedures来执行CRUD操作

时间:2017-03-09 18:13:20

标签: asp.net-mvc-5 entity-framework-6 unit-of-work

我正在使用MVC数据库第一种方法创建应用程序。我一直在创建基于使用上下文进行CRUD操作的数据访问层。 我一直在使用Entity Framework,Generic Repository模式和UnitOfWork模式。它是否会影响我实施的模式。

突然间我被告知CRUD操作需要使用存储过程来完成。有人可以告诉我如何将其合并到我当前的代码中。给我的一个推理是团队使用SQL很舒服,因此他们更喜欢使用存储过程。

通用存储库

public class GenericRepository<TEntity> where TEntity : class
    {
        #region Private member variables...
        internal AppointmentBookingContext Context;
        internal DbSet<TEntity> DbSet;
        #endregion

        #region Public Constructor...
        /// <summary>
        /// Public Constructor,initializes privately declared local variables.
        /// </summary>
        /// <param name="context"></param>
        public GenericRepository(AppointmentBookingContext context)
        {
            this.Context = context;
            this.DbSet = context.Set<TEntity>();
        }
        #endregion

        #region Public member methods...

        /// <summary>
        /// generic Get method for Entities
        /// </summary>
        /// <returns></returns>
        public virtual IEnumerable<TEntity> Get()
        {
            IQueryable<TEntity> query = DbSet;
            return query.ToList();
        }

        /// <summary>
        /// Generic get method on the basis of id for Entities.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual TEntity GetByID(object id)
        {
            return DbSet.Find(id);
        }

        /// <summary>
        /// generic Insert method for the entities
        /// </summary>
        /// <param name="entity"></param>
        public virtual void Insert(TEntity entity)
        {
            DbSet.Add(entity);
        }

     }

工作单元

namespace AppointmentBooking.Data.UnitOfWork
{
    public class UnitOfWork : IDisposable, IUnitOfWork
    {
        #region Private member variables...

        private AppointmentBookingContext _context = null;

        private GenericRepository<Patient> _patientRepository;
        private GenericRepository<Practioner> _practionerRepository;
        private GenericRepository<Appointment> _appointmentRepository;
        private GenericRepository<AppointmentType> _appointmentTypeRepository;
        private GenericRepository<PractionerType> _practionerTypeRepository;
        private GenericRepository<PractionerAvailableHours> _practionerAvailabeHoursRepository;



        #endregion

        public UnitOfWork()
        {
            _context = new AppointmentBookingContext();
        }

        #region Public Repository Creation properties...

        /// <summary>
        /// Get/Set Property for Patient repository.
        /// </summary>
        public GenericRepository<Patient> PatientRepository
        {
            get
            {
                if (this._patientRepository == null)
                    this._patientRepository = new GenericRepository<Patient>(_context);
                return _patientRepository;
            }
        }

        /// <summary>
        /// Get/Set Property for Practioner repository.
        /// </summary>
        public GenericRepository<Practioner> PractionerRepository
        {
            get
            {
                if (this._practionerRepository == null)
                    this._practionerRepository = new GenericRepository<Practioner>(_context);
                return _practionerRepository;
            }
        }


        #endregion





        #region Public member methods...
        /// <summary>
        /// Save method.
        /// </summary>
        public void Save()
        {
            try
            {
                _context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {

                var outputLines = new List<string>();
                foreach (var eve in e.EntityValidationErrors)
                {
                    outputLines.Add(string.Format(
                        "{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:", DateTime.Now,
                        eve.Entry.Entity.GetType().Name, eve.Entry.State));
                    foreach (var ve in eve.ValidationErrors)
                    {
                        outputLines.Add(string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage));
                    }
                }
                System.IO.File.AppendAllLines(@"C:\errors.txt", outputLines);

                throw e;
            }

        }

        #endregion

        #region Implementing IDiosposable...

        #region private dispose variable declaration...
        private bool disposed = false;
        #endregion

        /// <summary>
        /// Protected Virtual Dispose method
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    Debug.WriteLine("UnitOfWork is being disposed");
                    _context.Dispose();
                }
            }
            this.disposed = true;
        }

        /// <summary>
        /// Dispose method
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion
    }
}

业务层

  public class PatientService : IPatientService
    {

        private readonly IUnitOfWork _unitOfWork;

        public PatientService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public int CreatePatient(PatientDto patientDto)
        {
            using (var scope = new TransactionScope())
            {
                var patient = new Patient
                {
                    FirstName = patientDto.FirstName,
                    LastName = patientDto.LastName,
                    Email = patientDto.Email,
                    Gender = patientDto.Gender,
                    Address = patientDto.Address,
                    City = patientDto.City,
                    State = patientDto.State,
                    PostCode = patientDto.PostCode,
                    Phone = patientDto.Phone,
                    DateOfBirth = patientDto.DateOfBirth,
                    CreatedDate = patientDto.CreatedDate,
                    ModifiedDate = patientDto.ModifiedDate,
                    Id = patientDto.Id

                };


                _unitOfWork.PatientRepository.Insert(patient);
                _unitOfWork.Save();
                scope.Complete();
                return patient.Id;
            }
        }

        public bool DeletePatient(int id)
        {
            var success = false;

            if (id > 0)
            {
                using (var scope = new TransactionScope())
                {
                    var patient = _unitOfWork.PatientRepository.GetByID(id);
                    if (patient != null)
                    {

                        _unitOfWork.PatientRepository.Delete(patient);
                        _unitOfWork.Save();
                        scope.Complete();
                        success = true;
                    }
                }
            }
            return success;
        }

        public IEnumerable<PatientDto> GetPatient()
        {
            var patient = _unitOfWork.PatientRepository.GetAll();
            if (patient != null)
            {
                var patientDto = new List<PatientDto>();
                foreach (var p in patient)
                {
                    yield return Mapper.Map<PatientDto>(p);
                }
            }
            yield break;
        }
}

0 个答案:

没有答案