EF Core 仓储模式

数据库:SqlServer为例

安装包:

 

数据库连接

DbContext

public class TestDbContext:DbContext
{
    public TestDbContext(DbContextOptions<TestDbContext> options) : base(options)
    {
    }
    public DbSet<User> Users { get; set; }
}

注册数据库上下文

builder.Services.AddDbContext<TestDbContext>(options =>
 {
     options.UseSqlServer("ConnectionString");
 });
 //依赖注入仓储
 builder.Services.AddTransient(typeof(IRepository<>),typeof(BaseRepository<>));

 

仓储接口----IRepository

public interface IRepository<T>  where T : class
{
    /// <summary>
    /// 新增
    /// </summary>
    /// <param name="t">要新增的信息</param>
    void Insert(T t);
    /// <summary>
    /// 新增
    /// </summary>
    /// <param name="t">要新增的信息</param>
    Task InsertAsync(T t);
    /// <summary>
    /// 批量新增
    /// </summary>
    /// <param name="t">要新增的信息</param>
    void InsertRange(List<T> t);
    /// <summary>
    /// 批量新增
    /// </summary>
    /// <param name="t">要新增的信息</param>
    Task InsertRangeAsync(List<T> t);
    /// <summary>
    /// 更新单个对象
    /// </summary>
    /// <param name="t">要更改的信息</param>
    void Update(T t);

    /// <summary>
    /// 单个更新对象-异步
    /// </summary>
    /// <param name="t">要更改的信息</param>
    Task UpdateAsync(T t);
    /// <summary>
    /// 批量更新
    /// </summary>
    /// <param name="t">要修改的信息</param>
    void UpdateRange(List<T> t);
    /// <summary>
    /// 批量更新-异步
    /// </summary>
    /// <param name="t">要修改的信息</param>
    Task UpdateRangeAsync(List<T> t);
    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="t">要删除的信息</param>
    void Delete(T t);
    /// <summary>
    /// 删除-异步
    /// </summary>
    /// <param name="t">要删除的信息</param>
    Task DeleteAsync(T t);
    /// <summary>
    /// 批量删除
    /// </summary>
    /// <param name="t">要删除的信息</param>
    void DeleteRange(List<T> t);
    /// <summary>
    /// 批量删除-异步
    /// </summary>
    /// <param name="t">要删除的信息</param>
    Task DeleteRangeAsync(List<T> t);
    /// <summary>
    /// 单个查询
    /// </summary>
    /// <param name="id">要获取对象的编号</param>
    /// <returns>对象</returns>
    T Get(int id);

    /// <summary>
    /// 单个查询=异步
    /// </summary>
    /// <param name="id">要获取对象的编号</param>
    /// <returns></returns>
    Task<T> GetAsync(int id);
    /// <summary>
    /// 获取对象列表
    /// </summary>
    /// <returns>对象集合</returns>
   IQueryable<T> GetAll();
   
    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="pageindex">页码</param>
    /// <param name="pagesize">每页获取数量</param>
    /// <param name="where">条件查询</param>
    /// <param name="orderBy">条件排序</param>
    /// <param name="orderAsc">true 升序</param>
    /// <param name="totalcount">总条数</param>
    /// <returns>对象集合</returns>
    IQueryable<T> GetPage(int pageindex, int pagesize, Func<T, bool> where, Func<T, DateTime> orderBy, bool orderAsc, out int totalcount);
}

 

仓储实现---BaseRepository

public class BaseRepository<T> : IRepository<T> where T : class, new()
{
    private readonly TestDbContext _context;

    public BaseRepository(TestDbContext context)
    {
        _context = context;
    }
    #region 删除
    /// <summary>
    /// 单个删除
    /// </summary>
    /// <param name="t">带主键的实体</param>
    public void Delete(T t)
    {
        _context.Remove(t);
    }

    /// <summary>
    /// 单个删除-异步
    /// </summary>
    /// <param name="t">带主键的实体</param>
    /// <returns></returns>
    public async Task DeleteAsync(T t)
    {
        await Task.Run(() => _context.Remove(t));
    }

    /// <summary>
    /// 批量删除
    /// </summary>
    /// <param name="t">带主键的实体集合</param>
    public void DeleteRange(List<T> t)
    {
        _context.RemoveRange(t);
    }

    /// <summary>
    /// 批量删除-异步
    /// </summary>
    /// <param name="t">带主键的实体集合</param>
    /// <returns></returns>
    public async Task DeleteRangeAsync(List<T> t)
    {
        await Task.Run(() => _context.Set<T>().RemoveRange(t));
    }
    #endregion

    #region 查询

    /// <summary>
    /// 单个查询
    /// </summary>
    /// <param name="id">主键</param>
    /// <returns></returns>
    public T Get(int id)
    {
        return _context.Find<T>(id) ?? new T();
    }
    /// <summary>
    /// 集合查询
    /// </summary>
    /// <returns></returns>
    public IQueryable<T> GetAll()
    {
        return _context.Set<T>().AsNoTracking();
    }
    /// <summary>
    /// 单个查询-异步
    /// </summary>
    /// <param name="id">主键</param>
    /// <returns></returns>
    public async Task<T> GetAsync(int id)
    {
        return await _context.FindAsync<T>(id) ?? new T();
    }
    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="pageindex">页码</param>
    /// <param name="pagesize">每页获取数量</param>
    /// <param name="where"></param>
    /// <param name="orderBy"></param>
    /// <param name="orderAsc"></param>
    /// <param name="totalcount">结果总条数</param>
    /// <returns></returns>
    public IQueryable<T> GetPage(int pageindex, int pagesize, Func<T, bool> where, Func<T, DateTime> orderBy, bool orderAsc, out int totalcount)
    {
        var query = GetAll().Where(where);
        if (orderAsc)
        {
            query = query.OrderBy(orderBy);
            //query = query.OrderBy(orderBy).AsQueryable();
        }
        else
        {
            query = query.OrderBy(orderBy);
            //query = query.OrderByDescending(orderBy).AsQueryable() ;
        }
        totalcount = query.Count();
        return query.Skip((pageindex - 1) * pagesize).Take(pagesize).AsQueryable();
    }
    #endregion

    #region 新增
    /// <summary>
    /// 新增
    /// </summary>
    /// <param name="t"></param>
    public void Insert(T t)
    {
        _context.Add(t);
    }

    /// <summary>
    /// 单个新增
    /// </summary>
    /// <param name="t"></param>
    /// <returns></returns>
    public async Task InsertAsync(T t)
    {
        await _context.AddAsync(t);
    }

    /// <summary>
    /// 批量新增
    /// </summary>
    /// <param name="t"></param>
    public void InsertRange(List<T> t)
    {
        _context.AddRange(t);
    }

    /// <summary>
    /// 批量新增-异步
    /// </summary>
    /// <param name="t"></param>
    /// <returns></returns>
    public async Task InsertRangeAsync(List<T> t)
    {
        await _context.AddRangeAsync(t);
    }

    #endregion

    #region 更新
    /// <summary>
    /// 更新单个对象
    /// </summary>
    /// <param name="t">更新对象</param>
    public void Update(T t)
    {
        _context.Update(t);
    }

    /// <summary>
    /// 更新单个对象-异步
    /// </summary>
    /// <param name="t">更新对象</param>
    /// <returns></returns>
    public async Task UpdateAsync(T t)
    {
        await Task.Run(() => { _context.Update(t); });
    }

    /// <summary>
    /// 批量更新
    /// </summary>
    /// <param name="t"></param>
    public void UpdateRange(List<T> t)
    {
        _context.UpdateRange(t);
    }

    /// <summary>
    /// 批量更新-异步
    /// </summary>
    /// <param name="t"></param>
    /// <returns></returns>
    public async Task UpdateRangeAsync(List<T> t)
    {
        await Task.Run(() => { _context.UpdateRange(); });
    }
    #endregion

    public bool SaveChange()
    {
        return _context.SaveChanges() > 0;
    }
    public async Task<bool> SaveChangeAsync()
    {
        return await _context.SaveChangesAsync() > 0;
    }
}

 

仓储使用

public class UserService: IUserService
{
    private readonly IRepository<User> _userRepository;

    public UserService(IRepository<User> userRepository)
    {
        _userRepository = userRepository;
    }

    public async Task GetUsers(string name)
    {
        var result= await _userRepository.GetAll().Where(u => u.Name == name).ToListAsync();
    }
}

 

posted @ 2024-11-06 15:03  流年sugar  阅读(9)  评论(0编辑  收藏  举报