小白开学Asp.Net Core《二》

小白开学Asp.Net Core《二》

  ——数据仓储层(Repositroy

一、历史现象

  在后端开发中,数据库操作是最频繁的,每一个开发人员都会接触,甚至不少开发人员每天的工作就是与数据库打交道。所以可见数据库操作是多长重要。

  在现在的开发过程中,大多数开发人员只是以编写SQL语句的方式操作数据库,这种方式是操作数据库最原始的方式,简单高效,但是在编写SQL语句的过程中,极容易因粗心大意写出BUG,这样就会出现一种现象,开发人员面对一堆SQL语句的DEBUG,而且每次都需要开发人员自己去手写SQL语句,其开发效率极低。不同的数据库所需的SQL语句也还是有差异的,这就需要开发人员学习不同的数据库SQL语法。而且在项目开发中难免会遇到更换数据库的情况,这时还需要花费大量的精力去修改SQL语句。

二、数据仓储层

  由于以上缺点,所以仓储层因此而生。

  数据仓储层主要是对数据库操作CRUD的封装。使开发人员进行CRUD只需要极为简单的代码即可完成。本层还提供了数据库事务的支持,为数据库操作提供必备的保障。使用本层提供的接口,无需关心具体的业务逻辑实现,哪怕更换数据库,也无需更改业务逻辑代码,只需要更改简单的数据库配置即可。总之,本层为开发人员对数据库的操作提供了简单高效的操作接口。


三、继承关系图

   (继承图) 

  (接口定义)

 

 四、代码实现

   

 1 #region Async
 2         /// <summary>
 3         /// 查询所有数据(无分页,请慎用)
 4         /// </summary>
 5         /// <returns></returns>
 6         Task<IEnumerable<T>> FindAllAsync();
 7 
 8         /// <summary>
 9         /// 根据条件查询数据
10         /// </summary>
11         /// <param name="predicate">条件表达式树</param>
12         /// <param name="orderBy">排序</param>
13         /// <returns>泛型实体集合</returns>
14         Task<IEnumerable<T>> FindListByClauseAsync(Expression<Func<T, bool>> predicate, string orderBy = "");
15 
16         Task<IEnumerable<T>> PageQueryAsync(Expression<Func<T, bool>> predicate, int skip = 0, int pageSize = 15, string orderBy = "");
17         Task<T> FindByClauseAsync(Expression<Func<T, bool>> predicate);
18         /// <summary>
19         /// 插入实体数据
20         /// </summary>
21         /// <param name="entity"></param>
22         /// <returns></returns>
23         Task<int> InsertAsync(T entity);
24         /// <summary>
25         /// 更新实体数据
26         /// </summary>
27         /// <param name="entity"></param>
28         /// <returns></returns>
29         Task<bool> UpdateAsync(T entity);
30         /// <summary>
31         /// DeleteAsync
32         /// </summary>
33         /// <param name="entity"></param>
34         /// <returns></returns>
35         Task<bool> DeleteAsync(T entity);
36         /// <summary>
37         /// DeleteAsync
38         /// </summary>
39         /// <param name="where">条件表达式</param>
40         /// <returns></returns>
41         Task<bool> DeleteAsync(Expression<Func<T, bool>> @where);
42         /// <summary>
43         /// DeleteByIdAsync
44         /// </summary>
45         /// <param name="id"></param>
46         /// <returns></returns>
47         Task<bool> DeleteByIdAsync(object id);
48         /// <summary>
49         /// DeleteByIdsAsync
50         /// </summary>
51         /// <param name="ids">ids</param>
52         /// <returns></returns>
53         Task<bool> DeleteByIdsAsync(object[] ids);
54         /// <summary>
55         /// InsertAsync
56         /// </summary>
57         /// <param name="t"></param>
58         /// <returns></returns>
59         Task<DbResult<Task<int>>> InsertAsync(List<T> t);
60         /// <summary>
61         /// DeleteByClauseAsync
62         /// </summary>
63         /// <param name="predicate"></param>
64         /// <returns></returns>
65         Task<int> DeleteByClauseAsync(Expression<Func<T, bool>> predicate);
66 
67         /// <summary>
68         /// 事务
69         /// </summary>
70         /// <param name="func"></param>
71         /// <returns></returns>
72         Task<DbResult<T>> UserTranAsync(Func<T> func);
73 
74         /// <summary>
75         /// 事务
76         /// </summary>
77         /// <param name="action"></param>
78         Task<DbResult<bool>> UserTranAsync(Action action);
79         #endregion

五、实现 

/// <summary>
    /// GenericRepositoryBase
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class GenericSqlSugarRepositoryBase<T> : ISqlSugarRepository<T> where T : class, new()
    {
        #region Sync
        /// <summary>
        /// 根据主键查询
        /// </summary>
        /// <param name="pkValue">主键</param>
        /// <returns></returns>
        public T FindById(object pkValue)
        {
            using (var db = DbFactory.DB)
            {
                return db.Queryable<T>().InSingle(pkValue);
            }
        }

        /// <summary>
        /// 查询所有数据(无分页,请慎用)
        /// </summary>
        /// <returns></returns>
        public IEnumerable<T> FindAll()
        {
            using (var db = DbFactory.DB)
            {
                return db.Queryable<T>().ToList();
            }
        }

        /// <summary>
        /// 根据条件查询数据
        /// </summary>
        /// <param name="predicate">条件表达式树</param>
        /// <param name="orderBy">排序</param>
        /// <returns>泛型实体集合</returns>
        public IEnumerable<T> FindListByClause(Expression<Func<T, bool>> predicate, string orderBy = "")
        {
            using (var db = DbFactory.DB)
            {
                var query = db.Queryable<T>().Where(predicate);
                if (!string.IsNullOrEmpty(orderBy))
                    query.OrderBy(orderBy);
                return query.ToList();
            }
        }

        /// <summary>
        /// 根据条件分页查询
        /// </summary>
        /// <param name="predicate">条件表达式树</param>
        /// <param name="skip"></param>
        /// <param name="pageSize"></param>
        /// <param name="orderBy"></param>
        /// <returns></returns>
        public IEnumerable<T> PageQuery(Expression<Func<T, bool>> predicate, int skip, int pageSize = 15,
            string orderBy = "")
        {
            using (var db = DbFactory.DB)
            {
                if (skip > 0)
                    skip = pageSize * skip;
                var query = db.Queryable<T>().Where(predicate).Skip(skip).Take(pageSize);
                if (!string.IsNullOrEmpty(orderBy))
                    query = query.OrderBy(orderBy);
                return query.ToList();
            }
        }

        /// <summary>
        /// 根据条件查询数据
        /// </summary>
        /// <param name="predicate">条件表达式树</param>
        /// <returns></returns>
        public T FindByClause(Expression<Func<T, bool>> predicate)
        {
            using (var db = DbFactory.DB)
            {
                return db.Queryable<T>().First(predicate);
            }
        }

        /// <summary>
        /// 写入实体数据
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public int Insert(T entity)
        {
            using (var db = DbFactory.DB)
            {
                return db.Insertable(entity).ExecuteCommand();
            }
        }

        /// <summary>
        /// 更新实体数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Update(T entity)
        {
            using (var db = DbFactory.DB)
            {
                return db.Updateable(entity).ExecuteCommand() > 0;
            }
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public bool Delete(T entity)
        {
            using (var db = DbFactory.DB)
            {
                return db.Deleteable(entity).ExecuteCommand() > 0;
            }
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="where">过滤条件</param>
        /// <returns></returns>
        public bool Delete(Expression<Func<T, bool>> @where)
        {
            using (var db = DbFactory.DB)
            {
                return db.Deleteable<T>(@where).ExecuteCommand() > 0;
            }
        }

        /// <summary>
        /// 删除指定ID的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteById(object id)
        {
            using (var db = DbFactory.DB)
            {
                return db.Deleteable<T>(id).ExecuteCommand() > 0;
            }
        }

        /// <summary>
        /// 删除指定ID集合的数据(批量删除)
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool DeleteByIds(object[] ids)
        {
            using (var db = DbFactory.DB)
            {
                return db.Deleteable<T>().In(ids).ExecuteCommand() > 0;
            }
        }

        /// <summary>
        /// 执行sql语句
        /// </summary>
        /// <param name="sql">sql 语句</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public IEnumerable<T> FindListBySql(string sql, object dynamic)
        {
            using (var db = DbFactory.DB)
            {
                return db.Ado.SqlQuery<T>(sql, dynamic);
            }
        }

        /// <summary>
        /// 批量插入 插入失败时 事务会自动回退
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public int Insert(List<T> t)
        {
            using (var db = DbFactory.DB)
            {
                return db.Ado.UseTran(() => db.Insertable(t.ToArray()).ExecuteCommand()).Data;
            }
        }

        /// <summary>
        /// 事务
        /// </summary>
        /// <param name="func"></param>
        /// <returns></returns>
        public DbResult<T> UserTran(Func<T> func)
        {
            using (var db = DbFactory.DB)
            {
                return db.Ado.UseTran(func.Invoke);
            }
        }

        /// <summary>
        /// 事务
        /// </summary>
        /// <param name="action"></param>
        public DbResult<bool> UserTran(Action action)
        {
            using (var db = DbFactory.DB)
            {
                return db.Ado.UseTran(action.Invoke);
            }
        }

        /// <summary>
        /// 根据条件批量删除
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public int DeleteByClause(Expression<Func<T, bool>> predicate)
        {
            using (var db = DbFactory.DB)
            {
                return db.Deleteable<T>().Where(predicate).ExecuteCommand();
            }
        }

        // void ShadowCopy(object a, object b);

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="pagination"></param>
        /// <returns></returns>
        public List<T> FindList(Expression<Func<T, bool>> predicate, Pagination pagination)
        {
            var isAsc = pagination.sord.ToLower() == "asc";
            string[] _order = pagination.sidx.Split(',');
            MethodCallExpression resultExp = null;
            using (var db = DbFactory.DB)
            {
                var tempData = db.Queryable<T>().Where(predicate).ToList().AsQueryable();
                foreach (string item in _order)
                {
                    string _orderPart = item;
                    _orderPart = Regex.Replace(_orderPart, @"\s+", " ");
                    string[] _orderArry = _orderPart.Split(' ');
                    string _orderField = _orderArry[0];
                    bool sort = isAsc;
                    if (_orderArry.Length == 2)
                    {
                        isAsc = _orderArry[1].ToUpper() == "ASC";
                    }
                    var parameter = Expression.Parameter(typeof(T), "t");
                    var property = typeof(T).GetProperty(_orderField);
                    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
                    var orderByExp = Expression.Lambda(propertyAccess, parameter);
                    resultExp = Expression.Call(typeof(Queryable), isAsc ? "OrderBy" : "OrderByDescending", new Type[] { typeof(T), property.PropertyType }, tempData.Expression, Expression.Quote(orderByExp));
                }
                tempData = tempData.Provider.CreateQuery<T>(resultExp);
                pagination.records = tempData.Count();
                tempData = tempData.Skip<T>(pagination.rows * (pagination.page - 1)).Take<T>(pagination.rows).AsQueryable();
                return tempData.ToList();
            }
        }
        #endregion

        #region Async
        /// <summary>
        /// 查询所有数据(无分页,请慎用)
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<T>> FindAllAsync()
        {
            using (var db = DbFactory.DB)
            {
                return await db.Queryable<T>().ToListAsync();
            }
        }

        /// <summary>
        /// 根据条件查询数据
        /// </summary>
        /// <param name="predicate">条件表达式树</param>
        /// <param name="orderBy">排序</param>
        /// <returns>泛型实体集合</returns>
        public async Task<IEnumerable<T>> FindListByClauseAsync(Expression<Func<T, bool>> predicate, string orderBy = "")
        {
            using (var db = DbFactory.DB)
            {
                var query = db.Queryable<T>().Where(predicate);
                if (!string.IsNullOrEmpty(orderBy))
                {
                    query = query.OrderBy(orderBy);
                }
                return await query.ToListAsync();
            }
        }

        public async Task<IEnumerable<T>> PageQueryAsync(Expression<Func<T, bool>> predicate, int skip = 0,
            int pageSize = 15, string orderBy = "")
        {
            using (var db = DbFactory.DB)
            {
                if (skip > 0)
                    skip = pageSize * skip;
                var query = db.Queryable<T>().Where(predicate).Skip(skip).Take(pageSize);
                if (!string.IsNullOrEmpty(orderBy))
                {
                    query = query.OrderBy(orderBy);
                }
                return await query.ToListAsync();
            }
        }

        public async Task<T> FindByClauseAsync(Expression<Func<T, bool>> predicate)
        {
            using (var db = DbFactory.DB)
            {
                return await db.Queryable<T>().FirstAsync(predicate);
            }
        }

        /// <summary>
        /// 插入实体数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> InsertAsync(T entity)
        {
            using (var db = DbFactory.DB)
            {
                return await db.Insertable(entity).ExecuteCommandAsync();
            }
        }

        /// <summary>
        /// 更新实体数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateAsync(T entity)
        {
            using (var db = DbFactory.DB)
            {
                return await db.Updateable(entity).ExecuteCommandAsync() > 0;
            }
        }

        /// <summary>
        /// DeleteAsync
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> DeleteAsync(T entity)
        {
            using (var db = DbFactory.DB)
            {
                return await db.Deleteable(entity).ExecuteCommandAsync() > 0;
            }
        }

        /// <summary>
        /// DeleteAsync
        /// </summary>
        /// <param name="where">条件表达式</param>
        /// <returns></returns>
        public async Task<bool> DeleteAsync(Expression<Func<T, bool>> @where)
        {
            using (var db = DbFactory.DB)
            {
                return await db.Deleteable(@where).ExecuteCommandAsync() > 0;
            }
        }

        /// <summary>
        /// DeleteByIdAsync
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteByIdAsync(object id)
        {
            using (var db = DbFactory.DB)
            {
                return await db.Deleteable<T>(id).ExecuteCommandAsync() > 0;
            }
        }

        /// <summary>
        /// DeleteByIdsAsync
        /// </summary>
        /// <param name="ids">ids</param>
        /// <returns></returns>
        public async Task<bool> DeleteByIdsAsync(object[] ids)
        {
            using (var db = DbFactory.DB)
            {
                return await db.Deleteable<T>().In(ids).ExecuteCommandAsync() > 0;
            }
        }

        /// <summary>
        /// InsertAsync
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<DbResult<Task<int>>> InsertAsync(List<T> t)
        {
            using (var db = DbFactory.DB)
            {
                return await db.Ado.UseTranAsync(async () => await db.Insertable(t.ToArray()).ExecuteCommandAsync());
            }
        }

        /// <summary>
        /// DeleteByClauseAsync
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public async Task<int> DeleteByClauseAsync(Expression<Func<T, bool>> predicate)
        {
            using (var db = DbFactory.DB)
            {
                return await db.Deleteable<T>().Where(predicate).ExecuteCommandAsync();
            }
        }

        /// <summary>
        /// 事务
        /// </summary>
        /// <param name="func"></param>
        /// <returns></returns>
        public async Task<DbResult<T>> UserTranAsync(Func<T> func)
        {
            using (var db = DbFactory.DB)
            {
                return await db.Ado.UseTranAsync(func.Invoke);
            }
        }

        /// <summary>
        /// 事务
        /// </summary>
        /// <param name="action"></param>
        public async Task<DbResult<bool>> UserTranAsync(Action action)
        {
            using (var db = DbFactory.DB)
            {
                return await db.Ado.UseTranAsync(action.Invoke);
            }
        }
        #endregion
    }

本篇就到这里,下篇将介绍业务逻辑层与仓储库之间的关系与实现

 

(本人坚信:学习是由浅到深的过程,先打基础)

  不喜勿喷!谢谢!

GitHub地址:

  https://github.com/AjuPrince/Aju.Carefree

 

posted @ 2019-05-14 11:24  ZerekZhang  阅读(1682)  评论(0编辑  收藏  举报