.NetCore 3.1 EF Core 仓储模式+工作单元 以及其仓储原理

目录

  1. IRepository
  2. Repository
  3. IService
  4. Service
  5. Controller

IRepository

  1. IBaseRepository
public interface IBaseRepository<T> where T : class, new()
   {
        ValueTask<EntityEntry<T>> Insert(T entity);

        void Update(T entity);

        Task<int> Update(Expression<Func<T, bool>> whereLambda, Expression<Func<T, T>> entity);

        Task<int> Delete(Expression<Func<T, bool>> whereLambda);

        Task<bool> IsExist(Expression<Func<T, bool>> whereLambda);

        Task<T> GetEntity(Expression<Func<T, bool>> whereLambda);

        Task<List<T>> Select();

        Task<List<T>> Select(Expression<Func<T, bool>> whereLambda);

        Task<Tuple<List<T>, int>> Select<S>(int pageSize, int pageIndex, Expression<Func<T, bool>> whereLambda, Expression<Func<T, S>> orderByLambda, bool isAsc);
   }

 

  1. IUnitOfWork
public interface IUnitOfWork
   {
        MyDbContext GetDbContext();

        Task<int> SaveChangesAsync();
   }

 

  1. IStudentRepository
public interface IStudentRepository : IBaseRepository<Student>
  {
  }

 

Repository

  1. BaseRepository
 public class BaseRepository<T> where T : class, new()
    {
        private readonly MyDbContext myDbContext;

        public BaseRepository(MyDbContext myDbContext)
        {
            this.myDbContext = myDbContext;
        }

        public async ValueTask<EntityEntry<T>> Insert(T entity)
        {
            return await myDbContext.Set<T>().AddAsync(entity);
        }

        public void Update(T entity)
        {
            myDbContext.Set<T>().Update(entity);
        }

        public async Task<int> Update(Expression<Func<T, bool>> whereLambda, Expression<Func<T, T>> entity)
        {
            return await myDbContext.Set<T>().Where(whereLambda).UpdateAsync(entity);
        }

        public async Task<int> Delete(Expression<Func<T, bool>> whereLambda)
        {
            return await myDbContext.Set<T>().Where(whereLambda).DeleteAsync();
        }

        public async Task<bool> IsExist(Expression<Func<T, bool>> whereLambda)
        {
            return await myDbContext.Set<T>().AnyAsync(whereLambda);
        }

        public async Task<T> GetEntity(Expression<Func<T, bool>> whereLambda)
        {
            return await myDbContext.Set<T>().AsNoTracking().FirstOrDefaultAsync(whereLambda);
        }

        public async Task<List<T>> Select()
        {
            return await myDbContext.Set<T>().ToListAsync();
        }

        public async Task<List<T>> Select(Expression<Func<T, bool>> whereLambda)
        {
            return await myDbContext.Set<T>().Where(whereLambda).ToListAsync();
        }

        public async Task<Tuple<List<T>, int>> Select<S>(int pageSize, int pageIndex, Expression<Func<T, bool>> whereLambda, Expression<Func<T, S>> orderByLambda, bool isAsc)
        {
            var total = await myDbContext.Set<T>().Where(whereLambda).CountAsync();

            if (isAsc)
            {
                var entities = await myDbContext.Set<T>().Where(whereLambda)
                                      .OrderBy<T, S>(orderByLambda)
                                      .Skip(pageSize * (pageIndex - 1))
                                      .Take(pageSize).ToListAsync();

                return new Tuple<List<T>, int>(entities, total);
            }
            else
            {
                var entities = await myDbContext.Set<T>().Where(whereLambda)
                                      .OrderByDescending<T, S>(orderByLambda)
                                      .Skip(pageSize * (pageIndex - 1))
                                      .Take(pageSize).ToListAsync();

                return new Tuple<List<T>, int>(entities, total);
            }
        }
    }

 

  1. UnitOfWork
public class UnitOfWork : IUnitOfWork
  {
        private readonly MyDbContext myDbContext;

        public UnitOfWork(MyDbContext myDbContext)
        {
            this.myDbContext = myDbContext;
        }

        public MyDbContext GetDbContext()
        {
            return myDbContext;
        }

        public async Task<int> SaveChangesAsync()
        {
            return await myDbContext.SaveChangesAsync();
        }
   }

 

  1. StudentRepository
 public class StudentRepository : BaseRepository<Student>, IStudentRepository
  {
        public StudentRepository(MyDbContext myDbContext) : base(myDbContext)
        {
        }
  }

 

IService

  1. IBaseService
 public interface IBaseService<T> where T : class, new()
   {
        Task<int> Insert(T entity);

        Task<int> Update(T entity);

        Task<int> Update(Expression<Func<T, bool>> whereLambda, Expression<Func<T, T>> entity);

        Task<int> Delete(Expression<Func<T, bool>> whereLambda);

        Task<bool> IsExist(Expression<Func<T, bool>> whereLambda);

        Task<T> GetEntity(Expression<Func<T, bool>> whereLambda);

        Task<List<T>> Select();

        Task<List<T>> Select(Expression<Func<T, bool>> whereLambda);

        Task<Tuple<List<T>, int>> Select<S>(int pageSize, int pageIndex, Expression<Func<T, bool>> whereLambda, Expression<Func<T, S>> orderByLambda, bool isAsc);
    }

 

  1. IStudentService
public interface IStudentService : IBaseService<Student>
   {
        Task<bool> UOW(Student student, Teacher teacher);
   }

 

Service

  1. BaseService
public class BaseService<T> where T : class, new()
  {
        protected IUnitOfWork unitOfWork;
        protected IBaseRepository<T> currentRepository;

        public BaseService(IUnitOfWork unitOfWork, IBaseRepository<T> currentRepository)
        {
            this.unitOfWork = unitOfWork;
            this.currentRepository = currentRepository;
        }

        public async Task<int> Insert(T entity)
        {
            await currentRepository.Insert(entity);
            return await unitOfWork.SaveChangesAsync();
        }

        public async Task<int> Update(T entity)
        {
            currentRepository.Update(entity);
            return await unitOfWork.SaveChangesAsync();
        }

        public async Task<int> Update(Expression<Func<T, bool>> whereLambda, Expression<Func<T, T>> entity)
        {
            await currentRepository.Update(whereLambda, entity);
            return await unitOfWork.SaveChangesAsync();
        }

        public async Task<int> Delete(Expression<Func<T, bool>> whereLambda)
        {
            await currentRepository.Delete(whereLambda);
            return await unitOfWork.SaveChangesAsync();
        }

        public async Task<bool> IsExist(Expression<Func<T, bool>> whereLambda)
        {
            return await currentRepository.IsExist(whereLambda);
        }

        public async Task<T> GetEntity(Expression<Func<T, bool>> whereLambda)
        {
            return await currentRepository.GetEntity(whereLambda);
        }

        public async Task<List<T>> Select()
        {
            return await currentRepository.Select();
        }

        public async Task<List<T>> Select(Expression<Func<T, bool>> whereLambda)
        {
            return await currentRepository.Select(whereLambda);
        }

        public async Task<Tuple<List<T>, int>> Select<S>(int pageSize, int pageIndex, Expression<Func<T, bool>> whereLambda, Expression<Func<T, S>> orderByLambda, bool isAsc)
        {
            return await currentRepository.Select(pageSize, pageIndex, whereLambda, orderByLambda, isAsc);
        }
   }

 

  1. StudentService
public class StudentService : BaseService<Student>, IStudentService
  {
        private readonly ITeacherRepository teacherRepository;

        public StudentService(IUnitOfWork unitOfWork, IBaseRepository<Student> currentRepository, ITeacherRepository teacherRepository) : base(unitOfWork, currentRepository)

        {
            this.teacherRepository = teacherRepository;
        }

        public async Task<bool> UOW(Student student, Teacher teacher)
        {
            await currentRepository.Insert(student);
            await teacherRepository.Insert(teacher);

            await unitOfWork.SaveChangesAsync();

            return true;
        }
   }

 

Controller

  1. StudentController
[Route("api/[controller]/[action]")]
    [ApiController]
    public class StudentController : ControllerBase
    {
        private readonly IStudentService studentService;

        public StudentController(IStudentService studentService)
        {
            this.studentService = studentService;
        }

        [HttpPost]
        public async Task<string> Insert([FromForm] Student student)
        {
            try
            {
                await studentService.Insert(student);

                return new Response().ToJson();
            }
            catch (Exception e)
            {
                return new Response() { Code = 500, Message = e.Message }.ToJson();
            }
        }

        [HttpPost]
        public async Task<string> Update([FromForm] Student student)
        {
            try
            {
                //await studentService.Update(student);
                await studentService.Update(t => t.Sid == student.Sid, t => new Student() { Sage = student.Sage });

                return new Response().ToJson();
            }
            catch (Exception e)
            {
                return new Response() { Code = 500, Message = e.Message }.ToJson();
            }
        }

        [HttpPost]
        public async Task<string> Delete(int id)
        {
            try
            {
                await studentService.Delete(t => t.Sid == id);

                return new Response().ToJson();
            }
            catch (Exception e)
            {
                return new Response() { Code = 500, Message = e.Message }.ToJson();
            }
        }

        [HttpGet]
        public async Task<string> Select()
        {
            try
            {
                var students = await studentService.Select(t => true);
                return new Response<Student>() { Data = students }.ToJson();
            }
            catch (Exception e)
            {
                return new Response() { Code = 500, Message = e.Message }.ToJson();
            }
        }

        [HttpPost]
        public async Task<string> UOW([FromForm] Student student)
        {
            try
            {
                Teacher teacher = new Teacher() { Tid = student.Sid, Tname = student.Sname };

                await studentService.UOW(student, teacher);

                return new Response().ToJson();
            }
            catch (Exception e)
            {
                return new Response() { Code = 500, Message = e.Message }.ToJson();
            }
        }
    }

 

上一篇:css样式初始化以及rem布局


下一篇:【Vue】08 Webpack Part4 使用Vue