【无私分享:ASP.NET CORE 项目实战(第五章)】Repository仓储 UnitofWork

目录索引 

 

【无私分享:ASP.NET CORE 项目实战】目录索引

 

简介

 

  本章我们来创建仓储类Repository 并且引入 UnitOfWork

 

 

我对UnitOfWork的一些理解

 

   UnitOfWork 工作单元,对于这个的解释和实例,网上很多很多大神之作,我在这就不班门弄斧了,只是浅谈 一下个人理解,不一定对,希望大家指正:

  UnitOfWork 看了很多,个人理解就是 统一事务,在很多操作中我们可能是进行多项操作的,比如 同时保存两个表的数据,如果我们先保存一个表(SaveChanges()之后),再保存另一个表(SaveChanges())其实是两个不同的事务,通俗的讲,我们对数据库提交了两次数据。而UnitOfWork 就是 把本次操作(分别保存两张表)放在统一事务中,所有的CRUD完成后,统一提交数据,即保证数据的一致性,又减少了提交次数,提高性能。

  举个例子,我们之前的Repository的保存操作:

  Repository:

  public virtual bool Save(T entity)
  {
    _Context.Add(entity);
    return _Context.SaveChanges() > 0;
  }

 

  Controller: 

  public ActionResult Save()

  {

    var Users=new Users(){Id=1,UserName="张三"};

    var Logs=new Logs(){log="注册了用户张三"};

    _UserService.Save(Users);

    _LogService.Save(Logs);

  }

因为本身EF就是带事务的,但是_Context.SaveChanges()之后,事务就结束了,也提交了数据。所以,上面的例子 应该是开启了两次事务,提交了两次数据(一次是Users 一次是 Logs)

这显然是不合理的,首先不说提交两次数据性能的问题,如果用户注册失败,那么日志也不应该添加,应该回滚。但是,显然,上面没有这么做。

所以有了UnitOfWork。

使用UnitOfWork之后,代码应该是这样的:

 

  UnitOfWork:

  public bool Commit()
  {
    return _Context.SaveChanges() > 0; 
  }

 

  Repository:

  public virtual bool Save(T entity)
  {
    _Context.Add(entity);
  }

 

  Controller: 

  public ActionResult Save()

  {

    var Users=new Users(){Id=1,UserName="张三"};

    var Logs=new Logs(){log="注册了用户张三"};

    _UserService.Save(Users);

    _LogService.Save(Logs);

    _UnitOfWork.Commit();

  }

  

 

UnitOfWork接口和实现类

 我们在wkmvc.Core类库下,新建一个接口 IUnitOfWork:

复制代码
 1 namespace wkmvc.Core
 2 {
 3     /// <summary>
 4     /// Describe:工作单元接口
 5     /// Author:yuangang
 6     /// Date:2016/07/16
 7     /// Blogs:http://www.cnblogs.com/yuangang
 8     /// </summary>
 9     public interface IUnitOfWork
10     {
11         bool Commit();
12     }
13 }
复制代码

  

  IUnitOfWork 实现类 UnitOfWork:

复制代码
 1 using System;
 2 using wkmvc.Data;
 3 
 4 namespace wkmvc.Core
 5 {
 6     /// <summary>
 7     /// Describe:工作单元实现类
 8     /// Author:yuangang
 9     /// Date:2016/07/16
10     /// Blogs:http://www.cnblogs.com/yuangang
11     /// </summary>
12     public class UnitOfWork : IUnitOfWork, IDisposable
13     {
14         #region 数据上下文
15 
16         /// <summary>
17         /// 数据上下文
18         /// </summary>
19         private ApplicationDbContext _Context;
20         public UnitOfWork(ApplicationDbContext Context)
21         {
22             _Context = Context;
23         }
24 
25         #endregion
26 
27         public bool Commit()
28         {
29             return _Context.SaveChanges() > 0;
30         }
31 
32         public void Dispose()
33         {
34             if(_Context!=null)
35             {
36                 _Context.Dispose();
37             }
38             GC.SuppressFinalize(this);
39         }
40     }
41 }
复制代码

 

 

   这样,UnitOfWork 就完成了。下面我们来添加仓储:

 

仓储 IRepository、Repository

新建接口 IRepository 添加基本的操作方法:

 

复制代码
 1 using System;
 2 using System.Linq.Expressions;
 3 
 4 namespace wkmvc.Core
 5 {
 6     /// <summary>
 7     /// Describe:仓储接口
 8     /// Author:yuangang
 9     /// Date:2016/07/16
10     /// Blogs:http://www.cnblogs.com/yuangang
11     /// </summary>
12     /// <typeparam name="T">实体模型</typeparam>
13     public interface IRepository<T> where T : class
14     {
15         #region 单模型 CRUD 操作
16 
17         /// <summary>
18         /// 增加一条记录
19         /// </summary>
20         /// <param name="entity">实体模型</param>
21         /// <param name="IsCommit">是否提交(默认提交)</param>
22         /// <returns></returns>
23         bool Save(T entity, bool IsCommit = true);
24 
25         /// <summary>
26         /// 更新一条记录
27         /// </summary>
28         /// <param name="entity">实体模型</param>
29         /// <param name="IsCommit">是否提交(默认提交)</param>
30         /// <returns></returns>
31         bool Update(T entity, bool IsCommit = true);
32 
33         /// <summary>
34         /// 增加或更新一条记录
35         /// </summary>
36         /// <param name="entity">实体模型</param>
37         /// <param name="IsSave">是否增加</param>
38         /// <param name="IsCommit">是否提交(默认提交)</param>
39         /// <returns></returns>
40         bool SaveOrUpdate(T entity, bool IsSave, bool IsCommit = true);
41 
42         /// <summary>
43         /// 通过Lamda表达式获取实体
44         /// </summary>
45         /// <param name="predicate">Lamda表达式(p=>p.Id==Id)</param>
46         /// <returns></returns>
47         T Get(Expression<Func<T, bool>> predicate);
48 
49         /// <summary>
50         /// 删除一条记录
51         /// </summary>
52         /// <param name="entity">实体模型</param>
53         /// <param name="IsCommit">是否提交(默认提交)</param>
54         /// <returns></returns>
55         bool Delete(T entity, bool IsCommit = true);
56 
57         #endregion
58     }
59 }
复制代码

 

 

   实现类 Repository :

 

 

 

复制代码
  1 using Microsoft.EntityFrameworkCore;
  2 using System;
  3 using System.Linq;
  4 using System.Linq.Expressions;
  5 using wkmvc.Data;
  6 
  7 namespace wkmvc.Core
  8 {
  9     /// <summary>
 10     /// Describe:仓储实现类
 11     /// Author:yuangang
 12     /// Date:2016/07/16
 13     /// Blogs:http://www.cnblogs.com/yuangang
 14     /// </summary>
 15     /// <typeparam name="T">实体模型</typeparam>
 16     public abstract class Repository<T> : IRepository<T> where T : class
 17     {
 18         #region 数据上下文
 19 
 20         /// <summary>
 21         /// 数据上下文
 22         /// </summary>
 23         private ApplicationDbContext _Context;
 24 
 25         /// <summary>
 26         /// 工作单元
 27         /// </summary>
 28         UnitOfWork _UnitOfWork;
 29 
 30         public Repository(ApplicationDbContext Context)
 31         {
 32             _Context = Context;
 33             _UnitOfWork = new UnitOfWork(_Context);
 34         }
 35 
 36 
 37         #endregion
 38 
 39         #region 单模型 CRUD 操作
 40 
 41         /// <summary>
 42         /// 增加一条记录
 43         /// </summary>
 44         /// <param name="entity">实体模型</param>
 45         /// <param name="IsCommit">是否提交(默认提交)</param>
 46         /// <returns></returns>
 47         public virtual bool Save(T entity,bool IsCommit=true)
 48         {
 49             _Context.Add(entity);
 50             if (IsCommit)
 51                 return _UnitOfWork.Commit();
 52             else
 53                 return false;
 54         }
 55 
 56         /// <summary>
 57         /// 更新一条记录
 58         /// </summary>
 59         /// <param name="entity">实体模型</param>
 60         /// <param name="IsCommit">是否提交(默认提交)</param>
 61         /// <returns></returns>
 62         public virtual bool Update(T entity, bool IsCommit = true)
 63         {
 64             _Context.Attach(entity);
 65             _Context.Entry(entity).State = EntityState.Modified;
 66             if (IsCommit)
 67                 return _UnitOfWork.Commit();
 68             else
 69                 return false;
 70         }
 71 
 72         /// <summary>
 73         /// 增加或更新一条记录
 74         /// </summary>
 75         /// <param name="entity">实体模型</param>
 76         /// <param name="IsSave">是否增加</param>
 77         /// <param name="IsCommit">是否提交(默认提交)</param>
 78         /// <returns></returns>
 79         public virtual bool SaveOrUpdate(T entity, bool IsSave, bool IsCommit = true)
 80         {
 81             return IsSave ? Save(entity, IsCommit) : Update(entity, IsCommit);
 82         }
 83 
 84         /// <summary>
 85         /// 通过Lamda表达式获取实体
 86         /// </summary>
 87         /// <param name="predicate">Lamda表达式(p=>p.Id==Id)</param>
 88         /// <returns></returns>
 89         public virtual T Get(Expression<Func<T, bool>> predicate)
 90         {
 91             return _Context.Set<T>().AsNoTracking().SingleOrDefault(predicate);
 92         }
 93 
 94 
 95         /// <summary>
 96         /// 删除一条记录
 97         /// </summary>
 98         /// <param name="entity">实体模型</param>
 99         /// <param name="IsCommit">是否提交(默认提交)</param>
100         /// <returns></returns>
101         public virtual bool Delete(T entity, bool IsCommit = true)
102         {
103             if (entity == null) return false;
104             _Context.Remove(entity);
105 
106             if (IsCommit)
107                 return _UnitOfWork.Commit();
108             else
109                 return false;
110         }
111 
112         #endregion
113 
114 
115     }
116 }
复制代码

 

我们都添加了一个  bool IsCommit = true 参数,是为了方便,如果仅仅是进行一项操作,那就没必要使用 UnitOfWork 统一 直接 SaveChanages() 就行了

 

 

 

我们来看下使用: 

  //第一种
  public bool TestOne()
  {
    var users = new SYS_USER() { UserName="张三",Account="zhangsan",Password="123456" };

    return _UserService.Save(users);
  }


  //第二种
  public bool TestTwo()
  {
    var users1 = new SYS_USER() { UserName = "张三", Account = "zhangsan", Password = "123456" };
    var users2 = new SYS_USER() { UserName = "李四", Account = "lisi", Password = "456789" };
    var users3 = new SYS_USER() { UserName = "王五", Account = "wangwu", Password = "321654" };

    _UserService.Save(users1);
    _UserService.Save(users2);
    _UserService.Save(users3);

    return _UnitOfWork.Commit();
  }

 

本篇主要是介绍用法,具体的解释清大家参考大神们的讲解,如有不对的地方希望指正。具体的实现代码,我们后面一起一点一点写。

 

 

给大家贴一下个人实现的仓储 IRepository、Repository代码:

 

IRepository:

  1     public interface IRepository<T> where T : class
  2     {
  3         #region 单模型 CRUD 操作
  4 
  5         /// <summary>
  6         /// 增加一条记录
  7         /// </summary>
  8         /// <param name="entity">实体模型</param>
  9         /// <param name="IsCommit">是否提交(默认提交)</param>
 10         /// <returns></returns>
 11         bool Save(T entity, bool IsCommit = true);
 12         /// <summary>
 13         /// 增加一条记录(异步方式)
 14         /// </summary>
 15         /// <param name="entity">实体模型</param>
 16         /// <param name="IsCommit">是否提交(默认提交)</param>
 17         /// <returns></returns>
 18         Task<bool> SaveAsync(T entity, bool IsCommit = true);
 19 
 20         /// <summary>
 21         /// 更新一条记录
 22         /// </summary>
 23         /// <param name="entity">实体模型</param>
 24         /// <param name="IsCommit">是否提交(默认提交)</param>
 25         /// <returns></returns>
 26         bool Update(T entity, bool IsCommit = true);
 27         /// <summary>
 28         /// 更新一条记录(异步方式)
 29         /// </summary>
 30         /// <param name="entity">实体模型</param>
 31         /// <param name="IsCommit">是否提交(默认提交)</param>
 32         /// <returns></returns>
 33         Task<bool> UpdateAsync(T entity, bool IsCommit = true);
 34 
 35         /// <summary>
 36         /// 增加或更新一条记录
 37         /// </summary>
 38         /// <param name="entity">实体模型</param>
 39         /// <param name="IsSave">是否增加</param>
 40         /// <param name="IsCommit">是否提交(默认提交)</param>
 41         /// <returns></returns>
 42         bool SaveOrUpdate(T entity, bool IsSave, bool IsCommit = true);
 43         /// <summary>
 44         /// 增加或更新一条记录(异步方式)
 45         /// </summary>
 46         /// <param name="entity">实体模型</param>
 47         /// <param name="IsSave">是否增加</param>
 48         /// <param name="IsCommit">是否提交(默认提交)</param>
 49         /// <returns></returns>
 50         Task<bool> SaveOrUpdateAsync(T entity, bool IsSave, bool IsCommit = true);
 51 
 52         /// <summary>
 53         /// 通过Lamda表达式获取实体
 54         /// </summary>
 55         /// <param name="predicate">Lamda表达式(p=>p.Id==Id)</param>
 56         /// <returns></returns>
 57         T Get(Expression<Func<T, bool>> predicate);
 58         /// <summary>
 59         /// 通过Lamda表达式获取实体(异步方式)
 60         /// </summary>
 61         /// <param name="predicate">Lamda表达式(p=>p.Id==Id)</param>
 62         /// <returns></returns>
 63         Task<T> GetAsync(Expression<Func<T, bool>> predicate);
 64 
 65         /// <summary>
 66         /// 删除一条记录
 67         /// </summary>
 68         /// <param name="entity">实体模型</param>
 69         /// <param name="IsCommit">是否提交(默认提交)</param>
 70         /// <returns></returns>
 71         bool Delete(T entity, bool IsCommit = true);
 72         /// <summary>
 73         /// 删除一条记录(异步方式)
 74         /// </summary>
 75         /// <param name="entity">实体模型</param>
 76         /// <param name="IsCommit">是否提交(默认提交)</param>
 77         /// <returns></returns>
 78         Task<bool> DeleteAsync(T entity, bool IsCommit = true);
 79 
 80         #endregion
 81 
 82         #region 多模型 操作
 83 
 84         /// <summary>
 85         /// 增加多条记录,同一模型
 86         /// </summary>
 87         /// <param name="T1">实体模型集合</param>
 88         /// <param name="IsCommit">是否提交(默认提交)</param>
 89         /// <returns></returns>
 90         bool SaveList(List<T> T1, bool IsCommit = true);
 91         /// <summary>
 92         /// 增加多条记录,同一模型(异步方式)
 93         /// </summary>
 94         /// <param name="T1">实体模型集合</param>
 95         /// <param name="IsCommit">是否提交(默认提交)</param>
 96         /// <returns></returns>
 97         Task<bool> SaveListAsync(List<T> T1, bool IsCommit = true);
 98 
 99         /// <summary>
100         /// 增加多条记录,独立模型
101         /// </summary>
102         /// <param name="T1">实体模型集合</param>
103         /// <param name="IsCommit">是否提交(默认提交)</param>
104         /// <returns></returns>
105         bool SaveList<T1>(List<T1> T, bool IsCommit = true) where T1 : class;
106         /// <summary>
107         /// 增加多条记录,独立模型(异步方式)
108         /// </summary>
109         /// <param name="T1">实体模型集合</param>
110         /// <param name="IsCommit">是否提交(默认提交)</param>
111         /// <returns></returns>
112         Task<bool> SaveListAsync<T1>(List<T1> T, bool IsCommit = true) where T1 : class;
113 
114         /// <summary>
115         /// 更新多条记录,同一模型
116         /// </summary>
117         /// <param name="T1">实体模型集合</param>
118         /// <param name="IsCommit">是否提交(默认提交)</param>
119         /// <returns></returns>
120         bool UpdateList(List<T> T1, bool IsCommit = true);
121         /// <summary>
122         /// 更新多条记录,同一模型(异步方式)
123         /// </summary>
124         /// <param name="T1">实体模型集合</param>
125         /// <param name="IsCommit">是否提交(默认提交)</param>
126         /// <returns></returns>
127         Task<bool> UpdateListAsync(List<T> T1, bool IsCommit = true);
128 
129         /// <summary>
130         /// 更新多条记录,独立模型
131         /// </summary>
132         /// <param name="T1">实体模型集合</param>
133         /// <param name="IsCommit">是否提交(默认提交)</param>
134         /// <returns></returns>
135         bool UpdateList<T1>(List<T1> T, bool IsCommit = true) where T1 : class;
136         /// <summary>
137         /// 更新多条记录,独立模型(异步方式)
138         /// </summary>
139         /// <param name="T1">实体模型集合</param>
140         /// <param name="IsCommit">是否提交(默认提交)</param>
141         /// <returns></returns>
142         Task<bool> UpdateListAsync<T1>(List<T1> T, bool IsCommit = true) where T1 : class;
143 
144         /// <summary>
145         /// 删除多条记录,同一模型
146         /// </summary>
147         /// <param name="T1">实体模型集合</param>
148         /// <param name="IsCommit">是否提交(默认提交)</param>
149         /// <returns></returns>
150         bool DeleteList(List<T> T1, bool IsCommit = true);
151         /// <summary>
152         /// 删除多条记录,同一模型(异步方式)
153         /// </summary>
154         /// <param name="T1">实体模型集合</param>
155         /// <param name="IsCommit">是否提交(默认提交)</param>
156         /// <returns></returns>
157         Task<bool> DeleteListAsync(List<T> T1, bool IsCommit = true);
158 
159         /// <summary>
160         /// 删除多条记录,独立模型
161         /// </summary>
162         /// <param name="T1">实体模型集合</param>
163         /// <param name="IsCommit">是否提交(默认提交)</param>
164         /// <returns></returns>
165         bool DeleteList<T1>(List<T1> T, bool IsCommit = true) where T1 : class;
166         /// <summary>
167         /// 删除多条记录,独立模型(异步方式)
168         /// </summary>
169         /// <param name="T1">实体模型集合</param>
170         /// <param name="IsCommit">是否提交(默认提交)</param>
171         /// <returns></returns>
172         Task<bool> DeleteListAsync<T1>(List<T1> T, bool IsCommit = true) where T1 : class;
173 
174         /// <summary>
175         /// 通过Lamda表达式,删除一条或多条记录
176         /// </summary>
177         /// <param name="predicate"></param>
178         /// <param name="IsCommit"></param>
179         /// <returns></returns>
180         bool Delete(Expression<Func<T, bool>> predicate, bool IsCommit = true);
181         /// <summary>
182         /// 通过Lamda表达式,删除一条或多条记录(异步方式)
183         /// </summary>
184         /// <param name="predicate"></param>
185         /// <param name="IsCommit"></param>
186         /// <returns></returns>
187         Task<bool> DeleteAsync(Expression<Func<T, bool>> predicate, bool IsCommit = true);
188 
189         #endregion
190 
191         #region 获取多条数据操作
192 
193         /// <summary>
194         /// 返回IQueryable集合,延时加载数据
195         /// </summary>
196         /// <param name="predicate"></param>
197         /// <returns></returns>
198         IQueryable<T> LoadAll(Expression<Func<T, bool>> predicate);
199         /// <summary>
200         /// 返回IQueryable集合,延时加载数据(异步方式)
201         /// </summary>
202         /// <param name="predicate"></param>
203         /// <returns></returns>
204         Task<IQueryable<T>> LoadAllAsync(Expression<Func<T, bool>> predicate);
205 
206         // <summary>
207         /// 返回List<T>集合,不采用延时加载
208         /// </summary>
209         /// <param name="predicate"></param>
210         /// <returns></returns>
211         List<T> LoadListAll(Expression<Func<T, bool>> predicate);
212         // <summary>
213         /// 返回List<T>集合,不采用延时加载(异步方式)
214         /// </summary>
215         /// <param name="predicate"></param>
216         /// <returns></returns>
217         Task<List<T>> LoadListAllAsync(Expression<Func<T, bool>> predicate);
218 
219         /// <summary>
220         /// T-Sql方式:返回IQueryable<T>集合
221         /// </summary>
222         /// <param name="sql">SQL语句</param>
223         /// <param name="para">Parameters参数</param>
224         /// <returns></returns>
225         IQueryable<T> LoadAllBySql(string sql, params DbParameter[] para);
226         /// <summary>
227         /// T-Sql方式:返回IQueryable<T>集合(异步方式)
228         /// </summary>
229         /// <param name="sql">SQL语句</param>
230         /// <param name="para">Parameters参数</param>
231         /// <returns></returns>
232         Task<IQueryable<T>> LoadAllBySqlAsync(string sql, params DbParameter[] para);
233 
234         /// <summary>
235         /// T-Sql方式:返回List<T>集合
236         /// </summary>
237         /// <param name="sql">SQL语句</param>
238         /// <param name="para">Parameters参数</param>
239         /// <returns></returns>
240         List<T> LoadListAllBySql(string sql, params DbParameter[] para);
241         /// <summary>
242         /// T-Sql方式:返回List<T>集合(异步方式)
243         /// </summary>
244         /// <param name="sql">SQL语句</param>
245         /// <param name="para">Parameters参数</param>
246         /// <returns></returns>
247         Task<List<T>> LoadListAllBySqlAsync(string sql, params DbParameter[] para);
248 
249         /// <summary>
250         /// 可指定返回结果、排序、查询条件的通用查询方法,返回实体对象集合
251         /// </summary>
252         /// <typeparam name="TEntity">实体对象</typeparam>
253         /// <typeparam name="TOrderBy">排序字段类型</typeparam>
254         /// <typeparam name="TResult">数据结果,与TEntity一致</typeparam>
255         /// <param name="where">过滤条件,需要用到类型转换的需要提前处理与数据表一致的</param>
256         /// <param name="orderby">排序字段</param>
257         /// <param name="selector">返回结果(必须是模型中存在的字段)</param>
258         /// <param name="IsAsc">排序方向,true为正序false为倒序</param>
259         /// <returns>实体集合</returns>
260         List<TResult> QueryEntity<TEntity, TOrderBy, TResult>(Expression<Func<TEntity, bool>> where,Expression<Func<TEntity, TOrderBy>> orderby,Expression<Func<TEntity, TResult>> selector,bool IsAsc)
261             where TEntity : class
262             where TResult : class;
263         /// <summary>
264         /// 可指定返回结果、排序、查询条件的通用查询方法,返回实体对象集合(异步方式)
265         /// </summary>
266         /// <typeparam name="TEntity">实体对象</typeparam>
267         /// <typeparam name="TOrderBy">排序字段类型</typeparam>
268         /// <typeparam name="TResult">数据结果,与TEntity一致</typeparam>
269         /// <param name="where">过滤条件,需要用到类型转换的需要提前处理与数据表一致的</param>
270         /// <param name="orderby">排序字段</param>
271         /// <param name="selector">返回结果(必须是模型中存在的字段)</param>
272         /// <param name="IsAsc">排序方向,true为正序false为倒序</param>
273         /// <returns>实体集合</returns>
274         Task<List<TResult>> QueryEntityAsync<TEntity, TOrderBy, TResult>(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TOrderBy>> orderby, Expression<Func<TEntity, TResult>> selector, bool IsAsc)
275             where TEntity : class
276             where TResult : class;
277 
278         /// <summary>
279         /// 可指定返回结果、排序、查询条件的通用查询方法,返回Object对象集合
280         /// </summary>
281         /// <typeparam name="TEntity">实体对象</typeparam>
282         /// <typeparam name="TOrderBy">排序字段类型</typeparam>
283         /// <param name="where">过滤条件,需要用到类型转换的需要提前处理与数据表一致的</param>
284         /// <param name="orderby">排序字段</param>
285         /// <param name="selector">返回结果(必须是模型中存在的字段)</param>
286         /// <param name="IsAsc">排序方向,true为正序false为倒序</param>
287         /// <returns>自定义实体集合</returns>
288         List<object> QueryObject<TEntity, TOrderBy>(Expression<Func<TEntity, bool>> where,Expression<Func<TEntity, TOrderBy>> orderby,Func<IQueryable<TEntity>,List<object>> selector,bool IsAsc)
289             where TEntity : class;
290         /// <summary>
291         /// 可指定返回结果、排序、查询条件的通用查询方法,返回Object对象集合(异步方式)
292         /// </summary>
293         /// <typeparam name="TEntity">实体对象</typeparam>
294         /// <typeparam name="TOrderBy">排序字段类型</typeparam>
295         /// <param name="where">过滤条件,需要用到类型转换的需要提前处理与数据表一致的</param>
296         /// <param name="orderby">排序字段</param>
297         /// <param name="selector">返回结果(必须是模型中存在的字段)</param>
298         /// <param name="IsAsc">排序方向,true为正序false为倒序</param>
299         /// <returns>自定义实体集合</returns>
300         Task<List<object>> QueryObjectAsync<TEntity, TOrderBy>(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TOrderBy>> orderby, Func<IQueryable<TEntity>, List<object>> selector, bool IsAsc)
301             where TEntity : class;
302 
303         /// <summary>
304         /// 可指定返回结果、排序、查询条件的通用查询方法,返回动态类对象集合
305         /// </summary>
306         /// <typeparam name="TEntity">实体对象</typeparam>
307         /// <typeparam name="TOrderBy">排序字段类型</typeparam>
308         /// <param name="where">过滤条件,需要用到类型转换的需要提前处理与数据表一致的</param>
309         /// <param name="orderby">排序字段</param>
310         /// <param name="selector">返回结果(必须是模型中存在的字段)</param>
311         /// <param name="IsAsc">排序方向,true为正序false为倒序</param>
312         /// <returns>动态类</returns>
313         dynamic QueryDynamic<TEntity, TOrderBy>(Expression<Func<TEntity, bool>> where,Expression<Func<TEntity, TOrderBy>> orderby, Func<IQueryable<TEntity>,List<object>> selector,bool IsAsc)
314             where TEntity : class;
315         /// <summary>
316         /// 可指定返回结果、排序、查询条件的通用查询方法,返回动态类对象集合(异步方式)
317         /// </summary>
318         /// <typeparam name="TEntity">实体对象</typeparam>
319         /// <typeparam name="TOrderBy">排序字段类型</typeparam>
320         /// <param name="where">过滤条件,需要用到类型转换的需要提前处理与数据表一致的</param>
321         /// <param name="orderby">排序字段</param>
322         /// <param name="selector">返回结果(必须是模型中存在的字段)</param>
323         /// <param name="IsAsc">排序方向,true为正序false为倒序</param>
324         /// <returns>动态类</returns>
325         Task<dynamic> QueryDynamicAsync<TEntity, TOrderBy>(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TOrderBy>> orderby, Func<IQueryable<TEntity>, List<object>> selector, bool IsAsc)
326             where TEntity : class;
327 
328         #endregion
329 
330         #region 验证是否存在
331 
332         /// <summary>
333         /// 验证当前条件是否存在相同项
334         /// </summary>
335         bool IsExist(Expression<Func<T, bool>> predicate);
336         /// <summary>
337         /// 验证当前条件是否存在相同项(异步方式)
338         /// </summary>
339         Task<bool> IsExistAsync(Expression<Func<T, bool>> predicate);
340 
341         /// <summary>
342         /// 根据SQL验证实体对象是否存在
343         /// </summary>
344         bool IsExist(string sql, params DbParameter[] para);
345         /// <summary>
346         /// 根据SQL验证实体对象是否存在(异步方式)
347         /// </summary>
348         Task<bool> IsExistAsync(string sql, params DbParameter[] para);
349 
350         #endregion
351     }
View Code

 

Repository:

  1   public abstract class Repository<T> : IRepository<T> where T : class
  2     {
  3         #region 数据上下文
  4 
  5         /// <summary>
  6         /// 数据上下文
  7         /// </summary>
  8         private ApplicationDbContext _Context;       
  9 
 10         public Repository(ApplicationDbContext Context)
 11         {
 12             _Context = Context;
 13         }
 14 
 15         #endregion
 16 
 17         #region 单模型 CRUD 操作
 18 
 19         /// <summary>
 20         /// 增加一条记录
 21         /// </summary>
 22         /// <param name="entity">实体模型</param>
 23         /// <param name="IsCommit">是否提交(默认提交)</param>
 24         /// <returns></returns>
 25         public virtual bool Save(T entity,bool IsCommit=true)
 26         {
 27             _Context.Set<T>().Add(entity);
 28             if (IsCommit)
 29                 return _Context.SaveChanges() > 0;
 30             else
 31                 return false;
 32         }
 33         /// <summary>
 34         /// 增加一条记录(异步方式)
 35         /// </summary>
 36         /// <param name="entity">实体模型</param>
 37         /// <param name="IsCommit">是否提交(默认提交)</param>
 38         /// <returns></returns>
 39         public virtual async Task<bool> SaveAsync(T entity, bool IsCommit = true)
 40         {
 41             _Context.Set<T>().Add(entity);
 42             if (IsCommit)
 43                 return await Task.Run(() => _Context.SaveChanges() > 0);
 44             else
 45                 return await Task.Run(() => false); 
 46         }
 47 
 48         /// <summary>
 49         /// 更新一条记录
 50         /// </summary>
 51         /// <param name="entity">实体模型</param>
 52         /// <param name="IsCommit">是否提交(默认提交)</param>
 53         /// <returns></returns>
 54         public virtual bool Update(T entity, bool IsCommit = true)
 55         {
 56             _Context.Set<T>().Attach(entity);
 57             _Context.Entry<T>(entity).State = EntityState.Modified;
 58             if (IsCommit)
 59                 return _Context.SaveChanges() > 0;
 60             else
 61                 return false;
 62         }
 63         /// <summary>
 64         /// 更新一条记录(异步方式)
 65         /// </summary>
 66         /// <param name="entity">实体模型</param>
 67         /// <param name="IsCommit">是否提交(默认提交)</param>
 68         /// <returns></returns>
 69         public virtual async Task<bool> UpdateAsync(T entity, bool IsCommit = true)
 70         {
 71             _Context.Set<T>().Attach(entity);
 72             _Context.Entry<T>(entity).State = EntityState.Modified;
 73             if (IsCommit)
 74                 return await Task.Run(() => _Context.SaveChanges() > 0);
 75             else
 76                 return await Task.Run(() => false);
 77         }
 78 
 79         /// <summary>
 80         /// 增加或更新一条记录
 81         /// </summary>
 82         /// <param name="entity">实体模型</param>
 83         /// <param name="IsSave">是否增加</param>
 84         /// <param name="IsCommit">是否提交(默认提交)</param>
 85         /// <returns></returns>
 86         public virtual bool SaveOrUpdate(T entity, bool IsSave, bool IsCommit = true)
 87         {
 88             return IsSave ? Save(entity, IsCommit) : Update(entity, IsCommit);
 89         }
 90         /// <summary>
 91         /// 增加或更新一条记录(异步方式)
 92         /// </summary>
 93         /// <param name="entity">实体模型</param>
 94         /// <param name="IsSave">是否增加</param>
 95         /// <param name="IsCommit">是否提交(默认提交)</param>
 96         /// <returns></returns>
 97         public virtual async Task<bool> SaveOrUpdateAsync(T entity, bool IsSave, bool IsCommit = true)
 98         {
 99             return IsSave ? await SaveAsync(entity, IsCommit) : await UpdateAsync(entity, IsCommit);
100         }
101 
102         /// <summary>
103         /// 通过Lamda表达式获取实体
104         /// </summary>
105         /// <param name="predicate">Lamda表达式(p=>p.Id==Id)</param>
106         /// <returns></returns>
107         public virtual T Get(Expression<Func<T, bool>> predicate)
108         {
109             return _Context.Set<T>().AsNoTracking().SingleOrDefault(predicate);
110         }
111         /// <summary>
112         /// 通过Lamda表达式获取实体(异步方式)
113         /// </summary>
114         /// <param name="predicate">Lamda表达式(p=>p.Id==Id)</param>
115         /// <returns></returns>
116         public virtual async Task<T> GetAsync(Expression<Func<T, bool>> predicate)
117         {
118             return await Task.Run(()=> _Context.Set<T>().AsNoTracking().SingleOrDefault(predicate));
119         }
120 
121         /// <summary>
122         /// 删除一条记录
123         /// </summary>
124         /// <param name="entity">实体模型</param>
125         /// <param name="IsCommit">是否提交(默认提交)</param>
126         /// <returns></returns>
127         public virtual bool Delete(T entity, bool IsCommit = true)
128         {
129             if (entity == null) return false;
130             _Context.Set<T>().Attach(entity);
131             _Context.Set<T>().Remove(entity);
132 
133             if (IsCommit)
134                 return _Context.SaveChanges() > 0;
135             else
136                 return false;
137         }
138         /// <summary>
139         /// 删除一条记录(异步方式)
140         /// </summary>
141         /// <param name="entity">实体模型</param>
142         /// <param name="IsCommit">是否提交(默认提交)</param>
143         /// <returns></returns>
144         public virtual async Task<bool> DeleteAsync(T entity, bool IsCommit = true)
145         {
146             if (entity == null) return await Task.Run(() => false);
147             _Context.Set<T>().Attach(entity);
148             _Context.Set<T>().Remove(entity);
149             if (IsCommit)
150                 return  await Task.Run(() => _Context.SaveChanges() > 0);
151             else
152                 return await Task.Run(() => false); ;
153         }
154 
155         #endregion
156 
157         #region 多模型 操作
158 
159         /// <summary>
160         /// 增加多条记录,同一模型
161         /// </summary>
162         /// <param name="T1">实体模型集合</param>
163         /// <param name="IsCommit">是否提交(默认提交)</param>
164         /// <returns></returns>
165         public virtual bool SaveList(List<T> T1, bool IsCommit = true) 
166         {
167             if (T1 == null || T1.Count == 0) return false;
168 
169             T1.ToList().ForEach(item =>
170             {
171                 _Context.Set<T>().Add(item);
172             });
173 
174             if (IsCommit)
175                 return _Context.SaveChanges() > 0;
176             else
177                 return false;
178         }
179         /// <summary>
180         /// 增加多条记录,同一模型(异步方式)
181         /// </summary>
182         /// <param name="T1">实体模型集合</param>
183         /// <param name="IsCommit">是否提交(默认提交)</param>
184         /// <returns></returns>
185         public virtual async Task<bool> SaveListAsync(List<T> T1, bool IsCommit = true)
186         {
187             if (T1 == null || T1.Count == 0) return await Task.Run(() => false);
188 
189             T1.ToList().ForEach(item =>
190             {
191                 _Context.Set<T>().Add(item);
192             });
193 
194             if (IsCommit)
195                 return await Task.Run(() => _Context.SaveChanges() > 0);
196             else
197                 return await Task.Run(() => false);
198         }
199 
200         /// <summary>
201         /// 增加多条记录,独立模型
202         /// </summary>
203         /// <param name="T1">实体模型集合</param>
204         /// <param name="IsCommit">是否提交(默认提交)</param>
205         /// <returns></returns>
206         public virtual bool SaveList<T1>(List<T1> T, bool IsCommit = true) where T1 : class
207         {
208             if (T == null || T.Count == 0) return false;
209             var tmp = _Context.ChangeTracker.Entries<T>().ToList();
210             foreach (var x in tmp)
211             {
212                 var properties = typeof(T).GetTypeInfo().GetProperties();
213                 foreach (var y in properties)
214                 {
215                     var entry = x.Property(y.Name);
216                     entry.CurrentValue = entry.OriginalValue;
217                     entry.IsModified = false;
218                     y.SetValue(x.Entity, entry.OriginalValue);
219                 }
220                 x.State = EntityState.Unchanged;
221             }
222             T.ToList().ForEach(item =>
223             {
224                 _Context.Set<T1>().Add(item);
225             });
226             if (IsCommit)
227                 return _Context.SaveChanges() > 0;
228             else
229                 return false;
230         }
231         /// <summary>
232         /// 增加多条记录,独立模型(异步方式)
233         /// </summary>
234         /// <param name="T1">实体模型集合</param>
235         /// <param name="IsCommit">是否提交(默认提交)</param>
236         /// <returns></returns>
237         public virtual async Task<bool> SaveListAsync<T1>(List<T1> T, bool IsCommit = true) where T1 : class
238         {
239             if (T == null || T.Count == 0) return await Task.Run(() => false);
240             var tmp = _Context.ChangeTracker.Entries<T>().ToList();
241             foreach (var x in tmp)
242             {
243                 var properties = typeof(T).GetTypeInfo().GetProperties();
244                 foreach (var y in properties)
245                 {
246                     var entry = x.Property(y.Name);
247                     entry.CurrentValue = entry.OriginalValue;
248                     entry.IsModified = false;
249                     y.SetValue(x.Entity, entry.OriginalValue);
250                 }
251                 x.State = EntityState.Unchanged;
252             }
253             T.ToList().ForEach(item =>
254             {
255                 _Context.Set<T1>().Add(item);
256             });
257             if (IsCommit)
258                 return await Task.Run(() => _Context.SaveChanges() > 0);
259             else
260                 return await Task.Run(() => false);
261         }
262 
263         /// <summary>
264         /// 更新多条记录,同一模型
265         /// </summary>
266         /// <param name="T1">实体模型集合</param>
267         /// <param name="IsCommit">是否提交(默认提交)</param>
268         /// <returns></returns>
269         public virtual bool UpdateList(List<T> T1, bool IsCommit = true)
270         {
271             if (T1 == null || T1.Count == 0) return false;
272 
273             T1.ToList().ForEach(item =>
274             {
275                 _Context.Set<T>().Attach(item);
276                 _Context.Entry<T>(item).State = EntityState.Modified;
277             });
278 
279             if (IsCommit)
280                 return _Context.SaveChanges() > 0;
281             else
282                 return false;
283         }
284         /// <summary>
285         /// 更新多条记录,同一模型(异步方式)
286         /// </summary>
287         /// <param name="T1">实体模型集合</param>
288         /// <param name="IsCommit">是否提交(默认提交)</param>
289         /// <returns></returns>
290         public virtual async Task<bool> UpdateListAsync(List<T> T1, bool IsCommit = true)
291         {
292             if (T1 == null || T1.Count == 0) return await Task.Run(() => false);
293 
294             T1.ToList().ForEach(item =>
295             {
296                 _Context.Set<T>().Attach(item);
297                 _Context.Entry<T>(item).State = EntityState.Modified;
298             });
299 
300             if (IsCommit)
301                 return await Task.Run(() => _Context.SaveChanges() > 0);
302             else
303                 return await Task.Run(() => false);
304         }
305 
306         /// <summary>
307         /// 更新多条记录,独立模型
308         /// </summary>
309         /// <param name="T1">实体模型集合</param>
310         /// <param name="IsCommit">是否提交(默认提交)</param>
311         /// <returns></returns>
312         public virtual bool UpdateList<T1>(List<T1> T, bool IsCommit = true) where T1 : class
313         {
314             if (T == null || T.Count == 0) return false;
315 
316             T.ToList().ForEach(item =>
317             {
318                 _Context.Set<T1>().Attach(item);
319                 _Context.Entry<T1>(item).State = EntityState.Modified;
320             });
321 
322             if (IsCommit)
323                 return _Context.SaveChanges() > 0;
324             else
325                 return false;
326         }
327         /// <summary>
328         /// 更新多条记录,独立模型(异步方式)
329         /// </summary>
330         /// <param name="T1">实体模型集合</param>
331         /// <param name="IsCommit">是否提交(默认提交)</param>
332         /// <returns></returns>
333         public virtual async Task<bool> UpdateListAsync<T1>(List<T1> T, bool IsCommit = true) where T1 : class
334         {
335             if (T == null || T.Count == 0) return await Task.Run(() => false);
336 
337             T.ToList().ForEach(item =>
338             {
339                 _Context.Set<T1>().Attach(item);
340                 _Context.Entry<T1>(item).State = EntityState.Modified;
341             });
342 
343             if (IsCommit)
344                 return await Task.Run(() => _Context.SaveChanges() > 0);
345             else
346                 return await Task.Run(() => false);
347         }
348 
349         /// <summary>
350         /// 删除多条记录,同一模型
351         /// </summary>
352         /// <param name="T1">实体模型集合</param>
353         /// <param name="IsCommit">是否提交(默认提交)</param>
354         /// <returns></returns>
355         public virtual bool DeleteList(List<T> T1, bool IsCommit = true)
356         {
357             if (T1 == null || T1.Count == 0) return false;
358 
359             T1.ToList().ForEach(item =>
360             {
361                 _Context.Set<T>().Attach(item);
362                 _Context.Set<T>().Remove(item);
363             });
364 
365             if (IsCommit)
366                 return _Context.SaveChanges() > 0;
367             else
368                 return false;
369         }
370         /// <summary>
371         /// 删除多条记录,同一模型(异步方式)
372         /// </summary>
373         /// <param name="T1">实体模型集合</param>
374         /// <param name="IsCommit">是否提交(默认提交)</param>
375         /// <returns></returns>
376         public virtual async Task<bool> DeleteListAsync(List<T> T1, bool IsCommit = true)
377         {
378             if (T1 == null || T1.Count == 0) return await Task.Run(() => false);
379 
380             T1.ToList().ForEach(item =>
381             {
382                 _Context.Set<T>().Attach(item);
383                 _Context.Set<T>().Remove(item);
384             });
385 
386             if (IsCommit)
387                 return await Task.Run(() => _Context.SaveChanges() > 0);
388             else
389                 return await Task.Run(() => false);
390         }
391 
392         /// <summary>
393         /// 删除多条记录,独立模型
394         /// </summary>
395         /// <param name="T1">实体模型集合</param>
396         /// <param name="IsCommit">是否提交(默认提交)</param>
397         /// <returns></returns>
398         public virtual bool DeleteList<T1>(List<T1> T, bool IsCommit = true) where T1 : class
399         {
400             if (T == null || T.Count == 0) return false;
401 
402             T.ToList().ForEach(item =>
403             {
404                 _Context.Set<T1>().Attach(item);
405                 _Context.Set<T1>().Remove(item);
406             });
407 
408             if (IsCommit)
409                 return _Context.SaveChanges() > 0;
410             else
411                 return false;
412         }
413         /// <summary>
414         /// 删除多条记录,独立模型(异步方式)
415         /// </summary>
416         /// <param name="T1">实体模型集合</param>
417         /// <param name="IsCommit">是否提交(默认提交)</param>
418         /// <returns></returns>
419         public virtual async Task<bool> DeleteListAsync<T1>(List<T1> T, bool IsCommit = true) where T1 : class
420         {
421             if (T == null || T.Count == 0) return await Task.Run(() => false);
422 
423             T.ToList().ForEach(item =>
424             {
425                 _Context.Set<T1>().Attach(item);
426                 _Context.Set<T1>().Remove(item);
427             });
428 
429             if (IsCommit)
430                 return await Task.Run(() => _Context.SaveChanges() > 0);
431             else
432                 return await Task.Run(() => false);
433         }
434 
435         /// <summary>
436         /// 通过Lamda表达式,删除一条或多条记录
437         /// </summary>
438         /// <param name="predicate"></param>
439         /// <param name="IsCommit"></param>
440         /// <returns></returns>
441         public virtual bool Delete(Expression<Func<T, bool>> predicate, bool IsCommit = true)
442         {
443             IQueryable<T> entry = (predicate == null) ? _Context.Set<T>().AsQueryable() : _Context.Set<T>().Where(predicate);
444             List<T> list = entry.ToList();
445 
446             if (list != null && list.Count == 0) return false;
447             list.ForEach(item => {
448                 _Context.Set<T>().Attach(item);
449                 _Context.Set<T>().Remove(item);
450             });
451 
452             if (IsCommit)
453                 return _Context.SaveChanges() > 0;
454             else
455                 return false;
456         }
457         /// <summary>
458         /// 通过Lamda表达式,删除一条或多条记录(异步方式)
459         /// </summary>
460         /// <param name="predicate"></param>
461         /// <param name="IsCommit"></param>
462         /// <returns></returns>
463         public virtual async Task<bool> DeleteAsync(Expression<Func<T, bool>> predicate, bool IsCommit = true)
464         {
465             IQueryable<T> entry = (predicate == null) ? _Context.Set<T>().AsQueryable() : _Context.Set<T>().Where(predicate);
466             List<T> list = entry.ToList();
467 
468             if (list != null && list.Count == 0) return await Task.Run(() => false);
469             list.ForEach(item => {
470                 _Context.Set<T>().Attach(item);
471                 _Context.Set<T>().Remove(item);
472             });
473 
474             if (IsCommit)
475                 return await Task.Run(() => _Context.SaveChanges() > 0);
476             else
477                 return await Task.Run(() => false);
478         }
479 
480         #endregion
481 
482         #region 获取多条数据操作
483 
484         /// <summary>
485         /// Lamda返回IQueryable集合,延时加载数据
486         /// </summary>
487         /// <param name="predicate"></param>
488         /// <returns></returns>
489         public virtual IQueryable<T> LoadAll(Expression<Func<T, bool>> predicate)
490         {
491             return predicate != null ? _Context.Set<T>().Where(predicate).AsNoTracking<T>() : _Context.Set<T>().AsQueryable<T>().AsNoTracking<T>();            
492         }
493         /// <summary>
494         /// 返回IQueryable集合,延时加载数据(异步方式)
495         /// </summary>
496         /// <param name="predicate"></param>
497         /// <returns></returns>
498         public virtual async Task<IQueryable<T>> LoadAllAsync(Expression<Func<T, bool>> predicate)
499         {
500             return predicate != null ? await Task.Run(()=> _Context.Set<T>().Where(predicate).AsNoTracking<T>()) : await Task.Run(() => _Context.Set<T>().AsQueryable<T>().AsNoTracking<T>());
501         }
502 
503         /// <summary>
504         /// 返回List<T>集合,不采用延时加载
505         /// </summary>
506         /// <param name="predicate"></param>
507         /// <returns></returns>
508         public virtual List<T> LoadListAll(Expression<Func<T, bool>> predicate)
509         {
510             return predicate != null ? _Context.Set<T>().Where(predicate).AsNoTracking().ToList() : _Context.Set<T>().AsQueryable<T>().AsNoTracking().ToList();
511         }
512         // <summary>
513         /// 返回List<T>集合,不采用延时加载(异步方式)
514         /// </summary>
515         /// <param name="predicate"></param>
516         /// <returns></returns>
517         public virtual async Task<List<T>> LoadListAllAsync(Expression<Func<T, bool>> predicate)
518         {
519             return predicate != null ? await Task.Run(() => _Context.Set<T>().Where(predicate).AsNoTracking().ToList()) : await Task.Run(() => _Context.Set<T>().AsQueryable<T>().AsNoTracking().ToList());
520         }
521 
522         /// <summary>
523         /// T-Sql方式:返回IQueryable<T>集合
524         /// </summary>
525         /// <param name="sql">SQL语句</param>
526         /// <param name="para">Parameters参数</param>
527         /// <returns></returns>
528         public virtual IQueryable<T> LoadAllBySql(string sql, params DbParameter[] para)
529         {
530             return _Context.Set<T>().FromSql(sql, para);
531         }
532         /// <summary>
533         /// T-Sql方式:返回IQueryable<T>集合(异步方式)
534         /// </summary>
535         /// <param name="sql">SQL语句</param>
536         /// <param name="para">Parameters参数</param>
537         /// <returns></returns>
538         public virtual async Task<IQueryable<T>> LoadAllBySqlAsync(string sql, params DbParameter[] para)
539         {
540             return await Task.Run(() => _Context.Set<T>().FromSql(sql, para));
541         }
542 
543 
544         /// <summary>
545         /// T-Sql方式:返回List<T>集合
546         /// </summary>
547         /// <param name="sql">SQL语句</param>
548         /// <param name="para">Parameters参数</param>
549         /// <returns></returns>
550         public virtual List<T> LoadListAllBySql(string sql, params DbParameter[] para)
551         {
552             return _Context.Set<T>().FromSql(sql, para).Cast<T>().ToList();
553         }
554         /// <summary>
555         /// T-Sql方式:返回List<T>集合(异步方式)
556         /// </summary>
557         /// <param name="sql">SQL语句</param>
558         /// <param name="para">Parameters参数</param>
559         /// <returns></returns>
560         public virtual async Task<List<T>> LoadListAllBySqlAsync(string sql, params DbParameter[] para)
561         {
562             return await Task.Run(()=> _Context.Set<T>().FromSql(sql, para).Cast<T>().ToList());
563         }
564 
565         /// <summary>
566         /// 可指定返回结果、排序、查询条件的通用查询方法,返回实体对象集合
567         /// </summary>
568         /// <typeparam name="TEntity">实体对象</typeparam>
569         /// <typeparam name="TOrderBy">排序字段类型</typeparam>
570         /// <typeparam name="TResult">数据结果,与TEntity一致</typeparam>
571         /// <param name="where">过滤条件,需要用到类型转换的需要提前处理与数据表一致的</param>
572         /// <param name="orderby">排序字段</param>
573         /// <param name="selector">返回结果(必须是模型中存在的字段)</param>
574         /// <param name="IsAsc">排序方向,true为正序false为倒序</param>
575         /// <returns>实体集合</returns>
576         public virtual List<TResult> QueryEntity<TEntity, TOrderBy, TResult>
577             (Expression<Func<TEntity, bool>> where,
578             Expression<Func<TEntity, TOrderBy>> orderby,
579             Expression<Func<TEntity, TResult>> selector,
580             bool IsAsc)
581             where TEntity : class
582             where TResult : class
583         {
584             IQueryable<TEntity> query = _Context.Set<TEntity>();
585             if (where != null)
586             {
587                 query = query.Where(where);
588             }
589 
590             if (orderby != null)
591             {
592                 query = IsAsc ? query.OrderBy(orderby) : query.OrderByDescending(orderby);
593             }
594             if (selector == null)
595             {
596                 return query.Cast<TResult>().AsNoTracking().ToList();
597             }
598             return query.Select(selector).AsNoTracking().ToList();
599         }
600         /// <summary>
601         /// 可指定返回结果、排序、查询条件的通用查询方法,返回实体对象集合(异步方式)
602         /// </summary>
603         /// <typeparam name="TEntity">实体对象</typeparam>
604         /// <typeparam name="TOrderBy">排序字段类型</typeparam>
605         /// <typeparam name="TResult">数据结果,与TEntity一致</typeparam>
606         /// <param name="where">过滤条件,需要用到类型转换的需要提前处理与数据表一致的</param>
607         /// <param name="orderby">排序字段</param>
608         /// <param name="selector">返回结果(必须是模型中存在的字段)</param>
609         /// <param name="IsAsc">排序方向,true为正序false为倒序</param>
610         /// <returns>实体集合</returns>
611         public virtual async Task<List<TResult>> QueryEntityAsync<TEntity, TOrderBy, TResult>
612             (Expression<Func<TEntity, bool>> where,
613             Expression<Func<TEntity, TOrderBy>> orderby,
614             Expression<Func<TEntity, TResult>> selector,
615             bool IsAsc)
616             where TEntity : class
617             where TResult : class
618         {
619             IQueryable<TEntity> query = _Context.Set<TEntity>();
620             if (where != null)
621             {
622                 query = query.Where(where);
623             }
624 
625             if (orderby != null)
626             {
627                 query = IsAsc ? query.OrderBy(orderby) : query.OrderByDescending(orderby);
628             }
629             if (selector == null)
630             {
631                 return await Task.Run(() => query.Cast<TResult>().AsNoTracking().ToList());
632             }
633             return await Task.Run(() => query.Select(selector).AsNoTracking().ToList());
634         }
635 
636         /// <summary>
637         /// 可指定返回结果、排序、查询条件的通用查询方法,返回Object对象集合
638         /// </summary>
639         /// <typeparam name="TEntity">实体对象</typeparam>
640         /// <typeparam name="TOrderBy">排序字段类型</typeparam>
641         /// <param name="where">过滤条件,需要用到类型转换的需要提前处理与数据表一致的</param>
642         /// <param name="orderby">排序字段</param>
643         /// <param name="selector">返回结果(必须是模型中存在的字段)</param>
644         /// <param name="IsAsc">排序方向,true为正序false为倒序</param>
645         /// <returns>自定义实体集合</returns>
646         public virtual List<object> QueryObject<TEntity, TOrderBy>
647             (Expression<Func<TEntity, bool>> where,
648             Expression<Func<TEntity, TOrderBy>> orderby,
649             Func<IQueryable<TEntity>,
650             List<object>> selector,
651             bool IsAsc)
652             where TEntity : class
653         {
654             IQueryable<TEntity> query = _Context.Set<TEntity>();
655             if (where != null)
656             {
657                 query = query.Where(where);
658             }
659 
660             if (orderby != null)
661             {
662                 query = IsAsc ? query.OrderBy(orderby) : query.OrderByDescending(orderby);
663             }
664             if (selector == null)
665             {
666                 return query.AsNoTracking().ToList<object>();
667             }
668             return selector(query);
669         }
670         /// <summary>
671         /// 可指定返回结果、排序、查询条件的通用查询方法,返回Object对象集合(异步方式)
672         /// </summary>
673         /// <typeparam name="TEntity">实体对象</typeparam>
674         /// <typeparam name="TOrderBy">排序字段类型</typeparam>
675         /// <param name="where">过滤条件,需要用到类型转换的需要提前处理与数据表一致的</param>
676         /// <param name="orderby">排序字段</param>
677         /// <param name="selector">返回结果(必须是模型中存在的字段)</param>
678         /// <param name="IsAsc">排序方向,true为正序false为倒序</param>
679         /// <returns>自定义实体集合</returns>
680         public virtual async Task<List<object>> QueryObjectAsync<TEntity, TOrderBy>
681             (Expression<Func<TEntity, bool>> where,
682             Expression<Func<TEntity, TOrderBy>> orderby,
683             Func<IQueryable<TEntity>,
684             List<object>> selector,
685             bool IsAsc)
686             where TEntity : class
687         {
688             IQueryable<TEntity> query = _Context.Set<TEntity>();
689             if (where != null)
690             {
691                 query = query.Where(where);
692             }
693 
694             if (orderby != null)
695             {
696                 query = IsAsc ? query.OrderBy(orderby) : query.OrderByDescending(orderby);
697             }
698             if (selector == null)
699             {
700                 return await Task.Run(() => query.AsNoTracking().ToList<object>());
701             }
702             return await Task.Run(() => selector(query));
703         }
704 
705 
706         /// <summary>
707         /// 可指定返回结果、排序、查询条件的通用查询方法,返回动态类对象集合
708         /// </summary>
709         /// <typeparam name="TEntity">实体对象</typeparam>
710         /// <typeparam name="TOrderBy">排序字段类型</typeparam>
711         /// <param name="where">过滤条件,需要用到类型转换的需要提前处理与数据表一致的</param>
712         /// <param name="orderby">排序字段</param>
713         /// <param name="selector">返回结果(必须是模型中存在的字段)</param>
714         /// <param name="IsAsc">排序方向,true为正序false为倒序</param>
715         /// <returns>动态类</returns>
716         public virtual dynamic QueryDynamic<TEntity, TOrderBy>
717             (Expression<Func<TEntity, bool>> where,
718             Expression<Func<TEntity, TOrderBy>> orderby,
719             Func<IQueryable<TEntity>,
720             List<object>> selector,
721             bool IsAsc)
722             where TEntity : class
723         {
724             List<object> list = QueryObject<TEntity, TOrderBy>
725                  (where, orderby, selector, IsAsc);
726             return Common.JsonHelper.JsonConvert.JsonClass(list);
727         }
728         /// <summary>
729         /// 可指定返回结果、排序、查询条件的通用查询方法,返回动态类对象集合(异步方式)
730         /// </summary>
731         /// <typeparam name="TEntity">实体对象</typeparam>
732         /// <typeparam name="TOrderBy">排序字段类型</typeparam>
733         /// <param name="where">过滤条件,需要用到类型转换的需要提前处理与数据表一致的</param>
734         /// <param name="orderby">排序字段</param>
735         /// <param name="selector">返回结果(必须是模型中存在的字段)</param>
736         /// <param name="IsAsc">排序方向,true为正序false为倒序</param>
737         /// <returns>动态类</returns>
738         public virtual async Task<dynamic> QueryDynamicAsync<TEntity, TOrderBy>
739             (Expression<Func<TEntity, bool>> where,
740             Expression<Func<TEntity, TOrderBy>> orderby,
741             Func<IQueryable<TEntity>,
742             List<object>> selector,
743             bool IsAsc)
744             where TEntity : class
745         {
746             List<object> list = QueryObject<TEntity, TOrderBy>
747                  (where, orderby, selector, IsAsc);
748             return await Task.Run(() => Common.JsonHelper.JsonConvert.JsonClass(list)) ;
749         }
750 
751         #endregion
752 
753         #region 验证是否存在
754 
755         /// <summary>
756         /// 验证当前条件是否存在相同项
757         /// </summary>
758         public virtual bool IsExist(Expression<Func<T, bool>> predicate)
759         {
760             var entry = _Context.Set<T>().Where(predicate);
761             return (entry.Any());
762         }
763         /// <summary>
764         /// 验证当前条件是否存在相同项(异步方式)
765         /// </summary>
766         public virtual async Task<bool> IsExistAsync(Expression<Func<T, bool>> predicate)
767         {
768             var entry = _Context.Set<T>().Where(predicate);
769             return await Task.Run(() => entry.Any());
770         }
771 
772         /// <summary>
773         /// 根据SQL验证实体对象是否存在
774         /// </summary>
775         public virtual bool IsExist(string sql, params DbParameter[] para)
776         {
777             return _Context.Database.ExecuteSqlCommand(sql, para) > 0;
778         }
779         /// <summary>
780         /// 根据SQL验证实体对象是否存在(异步方式)
781         /// </summary>
782         public virtual async Task<bool> IsExistAsync(string sql, params DbParameter[] para)
783         {
784             return await Task.Run(() => _Context.Database.ExecuteSqlCommand(sql, para) > 0);
785         }
786 
787         #endregion
788 
789     }
View Code

 

 

 

 

 

希望跟大家一起学习Asp.net Core 

刚开始接触,水平有限,很多东西都是自己的理解和翻阅网上大神的资料,如果有不对的地方和不理解的地方,希望大家指正!

虽然Asp.net Core 现在很火热,但是网上的很多资料都是前篇一律的复制,所以有很多问题我也暂时没有解决,希望大家能共同帮助一下!

posted on 2016-08-25 21:18  張暁磊  阅读(475)  评论(0编辑  收藏  举报