.NetCore 3.1 EF Core 仓储模式+工作单元

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

IUnitOfWork

   public interface IUnitOfWork
   {
        MyDbContext GetDbContext();

        Task<int> SaveChangesAsync();
   }

IStudentRepository

  public interface IStudentRepository : IBaseRepository<Student>
  {
  }

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

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

StudentRepository

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

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

IStudentService

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

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

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
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();
        }
    }
}
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
.NET Core 3.1是微软开发的一种跨平台的开发框架,可以用于构建各种应用程序,包括Web应用、移动应用、桌面应用等。它具有高性能、可扩展、易于维护等特点,被广泛应用于各个领域。 API(Application Programming Interface)是一种软件架构,用于不同系统之间的互操作和通信。通过使用API,我们可以将不同的应用程序和服务连接起来,实现数据交互和功能共享。 MySQL是一种常用的开源关系型数据库管理系统。它具有高性能、稳定性和安全性,并支持多平台。在.NET Core 3.1中,我们可以通过使用MySQL数据库提供程序来操作MySQL数据库。 在.NET Core 3.1 API中使用MySQL数据库,我们可以按照以下步骤进行: 1. 首先,我们需要安装MySQL数据库,并创建一个数据库,用于存储数据。 2. 接着,我们需要在.NET Core 3.1项目中安装MySQL数据库提供程序。可以使用NuGet包管理器或在项目文件中添加对MySQL提供程序的引用。 3. 在项目中添加对MySQL数据库的连接字符串的配置,包括服务器地址、用户名、密码和数据库名称等。 4. 创建一个数据模型,用于定义数据库中的表和字段。 5. 使用Entity Framework Core来执行数据库操作,包括查询、插入、更新和删除等。 6. 在API的控制器中编写相应的接口,用于处理客户端的请求并与数据库进行交互。 7. 在启动文件中配置Web API的路由和Authentication。 通过以上步骤,我们就可以在.NET Core 3.1的API中使用MySQL数据库。使用MySQL数据库可以提供数据存储和检索的功能,使我们的API可以处理和管理数据。同时,由于.NET Core 3.1的跨平台特性,我们可以在不同的操作系统上部署和运行我们的API,实现应用程序的跨平台和多设备支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值