小白开学Asp.Net Core《二》

  ——数据仓储层(Repositroy

一、历史现象

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

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

二、数据仓储层

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

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

三、继承关系图

   (继承图) 

  (接口定义)

 四、代码实现

  

 #region Async
/// <summary>
/// 查询所有数据(无分页,请慎用)
/// </summary>
/// <returns></returns>
Task<IEnumerable<T>> FindAllAsync(); /// <summary>
/// 根据条件查询数据
/// </summary>
/// <param name="predicate">条件表达式树</param>
/// <param name="orderBy">排序</param>
/// <returns>泛型实体集合</returns>
Task<IEnumerable<T>> FindListByClauseAsync(Expression<Func<T, bool>> predicate, string orderBy = ""); Task<IEnumerable<T>> PageQueryAsync(Expression<Func<T, bool>> predicate, int skip = , int pageSize = , string orderBy = "");
Task<T> FindByClauseAsync(Expression<Func<T, bool>> predicate);
/// <summary>
/// 插入实体数据
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
Task<int> InsertAsync(T entity);
/// <summary>
/// 更新实体数据
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
Task<bool> UpdateAsync(T entity);
/// <summary>
/// DeleteAsync
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
Task<bool> DeleteAsync(T entity);
/// <summary>
/// DeleteAsync
/// </summary>
/// <param name="where">条件表达式</param>
/// <returns></returns>
Task<bool> DeleteAsync(Expression<Func<T, bool>> @where);
/// <summary>
/// DeleteByIdAsync
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
Task<bool> DeleteByIdAsync(object id);
/// <summary>
/// DeleteByIdsAsync
/// </summary>
/// <param name="ids">ids</param>
/// <returns></returns>
Task<bool> DeleteByIdsAsync(object[] ids);
/// <summary>
/// InsertAsync
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
Task<DbResult<Task<int>>> InsertAsync(List<T> t);
/// <summary>
/// DeleteByClauseAsync
/// </summary>
/// <param name="predicate"></param>
/// <returns></returns>
Task<int> DeleteByClauseAsync(Expression<Func<T, bool>> predicate); /// <summary>
/// 事务
/// </summary>
/// <param name="func"></param>
/// <returns></returns>
Task<DbResult<T>> UserTranAsync(Func<T> func); /// <summary>
/// 事务
/// </summary>
/// <param name="action"></param>
Task<DbResult<bool>> UserTranAsync(Action action);
#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 = ,
string orderBy = "")
{
using (var db = DbFactory.DB)
{
if (skip > )
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() > ;
}
} /// <summary>
/// 删除数据
/// </summary>
/// <param name="entity">实体类</param>
/// <returns></returns>
public bool Delete(T entity)
{
using (var db = DbFactory.DB)
{
return db.Deleteable(entity).ExecuteCommand() > ;
}
} /// <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() > ;
}
} /// <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() > ;
}
} /// <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() > ;
}
} /// <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[];
bool sort = isAsc;
if (_orderArry.Length == )
{
isAsc = _orderArry[].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 - )).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 = ,
int pageSize = , string orderBy = "")
{
using (var db = DbFactory.DB)
{
if (skip > )
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() > ;
}
} /// <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() > ;
}
} /// <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() > ;
}
} /// <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() > ;
}
} /// <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() > ;
}
} /// <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

小白开学Asp.Net Core《二》的更多相关文章

  1. 小白开学Asp.Net Core 《九》

    小白开学Asp.Net Core <九> — — 前端篇(不务正业) 在<小白开学Asp.Net Core 三>中使用了X-admin 2.x 和 Layui将管理后端的界面重 ...

  2. 小白开学Asp.Net Core 《四》

    小白开学Asp.Net Core<三>                               —— 使用AspectCore-Framework 一.AspectCore-Frame ...

  3. 小白开学Asp.Net Core 《五》

    小白开学Asp.Net Core<五>                               —— 使用.Net Core MVC Filter 一.简介 今天在项目(https:/ ...

  4. 小白开学Asp.Net Core 《六》

    小白开学Asp.Net Core <六> —— 探究.Net Core 跨平台的奥秘 1.写这篇文章的初衷 有好多朋友反馈看不懂我写的开源的一个练手项目(GitHub:https://gi ...

  5. 小白开学Asp.Net Core 《七》

    小白开学Asp.Net Core <七> — — 探究中间件(MiddleWare) 1.何为中间件? 中间件是组装到应用程序管道中以处理请求和响应的家伙,管道中的每个组件都要满足以下两个 ...

  6. 小白开学Asp.Net Core《三》

    小白开学Asp.Net Core<三> ——界面 我胡汉三再次又回来了(距离上篇时间有点长),今天抽时间将最近对框架采用的后台界面做个记录 1.先上图 (图一) (图二) 2.界面说明 后 ...

  7. 小白开学Asp.Net Core《二》(补)

    小白开学Asp.Net Core<二>(补) ——数据仓储层(Repositroy).服务层(Service) -------------------------------------- ...

  8. 小白开学Asp.Net Core 《十》

    小白开学Asp.Net Core <十> — — Session.Cookie.Cache(老生常谈) 一.背景 在常谈Session和Cookie之前我们先来简单的了解下Http(可以说 ...

  9. 小白开学Asp.Net Core 《八》

    小白开学Asp.Net Core <八> — — .Net Core 数据保护组件 1.背景 我在搞(https://github.com/AjuPrince/Aju.Carefree)这 ...

随机推荐

  1. Qt在各平台上的搭建qt-everywhere(Qt for windows7-64bit, Ubuntu 12.04-32bit, 嵌入式x86平台, 嵌入式arm平台)

    下载地址:http://download.qt.io/ 当进入解压好的源码包后,使用./configure –help命令,可以获得相应帮助,前面是*号的表示默认参数. +号表示该功能要求被评估,评估 ...

  2. WSAAsyncSelect Demo

    #include <WinSock2.h> #include <Windows.h> #include <StrSafe.h> #pragma comment(li ...

  3. Dynamics 365 Document Management

    Dynamics CRM中的Document Management功能需要Dynamics CRM与SharePoint进行集成,也就是实现在CRM中上传Document,实际上Document最终存 ...

  4. Android短视频中如何实现720P磨皮美颜录制?

    视频中磨皮.美颜功能已成为刚需,那么如何在Android短视频中实现720P磨皮美颜录制?本篇文章中,网易云信资深开发工程师将向大家介绍具体的操作方法. 相关阅读推荐 <短视频技术详解:Andr ...

  5. 视频直播:Windows中各类画面源的截取和合成方法总结

    当今,视频直播技术和实时音视频技术已经是很多行业必备,典型的应用场景有教育直播.远程视频会议.互联网娱乐等.在移动端发起直播,其画面源的种类是十分有限的,无非是取摄像头.截屏等.PC端由于其系统资源充 ...

  6. JavaScript 操作 DOM 总结

    基本概念 DOM 是 JavaScript 操作网页的接口,全称为"文档对象模型"(Document Object Model).它的作用是将网页转为一个 JavaScript 对 ...

  7. MAC 安装telnet

    https://blog.csdn.net/licheng70356213/article/details/81162660 在10.12及以下版本,都内置了telnet命令,但是在10.13中,已经 ...

  8. laravel扩展包-私有库

    创建一个新的laravel项目 composer create-project --prefer-dist laravel/laravel laravel-package "5.5.*&qu ...

  9. 微服务之服务注册与发现--Consul(转载)

    http://blog.csdn.net/buxiaoxia/article/details/69788114 https://www.cnblogs.com/xiaohanlin/p/8016803 ...

  10. vscode解决同步设置插件连接不上git

    vscode有一款比较好用的插件,就是设置同步.可以在一台电脑上同步另一台电脑的所有配置及插件! Settings Sync 但是在公司电脑有个奇葩问题,就是连接不上git. 解决:配置代理 &quo ...