博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ef core
阅读量:6154 次
发布时间:2019-06-21

本文共 26915 字,大约阅读时间需要 89 分钟。

using EFLogging;using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Infrastructure;using Microsoft.Extensions.Logging;using System;using System.Collections.Generic;using System.Data.Common;using System.Linq;using System.Linq.Expressions;using System.Reflection;using System.Text;using System.Threading.Tasks;namespace efcore.Repository{    public  class Repository
where T : class, new() { #region 数据上下文 ///
/// 数据上下文 /// private ApplicationDbContext _Context; public Repository(ApplicationDbContext Context) { _Context = Context; } #endregion #region 单模型 CRUD 操作 ///
/// 按照字段修改 /// /// /// //M.Id = 91; // M.CarNumber = "vvvvvvvvvvvvvvvv"; // M.CreateTime = DateTime.Now; // var properties = new Expression
>[2]; //properties[0] = d => d.CarNumber; // properties[1] = d => d.CreateTime; // CarBll.GetInstance().UpdateModified(M, properties); // 或 CarBll.GetInstance().UpdateModified(M, d => d.CarNumber, d => d.CreateTime); // 或 CarBll.GetInstance().UpdateModified(M, null); ///
///
///
///
//public virtual bool UpdateModified(T entity, bool IsCommit = true, params Expression
>[] properties) //{ // // _Context.Set
().Attach(entity); // _Context.Entry(entity).State = EntityState.Unchanged; // if (properties == null) // { // PropertyInfo[] props = entity.GetType().GetProperties(); // foreach (PropertyInfo prop in props) // { // _Context.Entry(entity).Property(prop.Name).IsModified = true; // } // } // else // { // foreach (var selector in properties) // { // _Context.Entry(entity).Property(selector).IsModified = true; // } // } // //foreach (var property in properties) // //{ // // var propertyName = ExpressionHelper.GetExpressionText(property); // // _context.Entry(entity).Property(propertyName).IsModified = true; // //} // if (IsCommit) // return _Context.SaveChanges() > 0; // else // return false; //} ///
/// 增加一条记录 /// ///
实体模型 ///
是否提交(默认提交) ///
public virtual bool Save(T entity, bool IsCommit = true) { _Context.Set
().Add(entity); if (IsCommit) return _Context.SaveChanges() > 0; else return false; } ///
/// 增加一条记录(异步方式) /// ///
实体模型 ///
是否提交(默认提交) ///
public virtual async Task
SaveAsync(T entity, bool IsCommit = true) { _Context.Set
().Add(entity); if (IsCommit) return await Task.Run(() => _Context.SaveChanges() > 0); else return await Task.Run(() => false); } ///
/// 更新一条记录 /// ///
实体模型 ///
是否提交(默认提交) ///
public virtual bool Update(T entity, bool IsCommit = true) { _Context.Set
().Attach(entity); _Context.Entry
(entity).State = EntityState.Modified; if (IsCommit) return _Context.SaveChanges() > 0; else return false; } ///
/// 更新一条记录(异步方式) /// ///
实体模型 ///
是否提交(默认提交) ///
public virtual async Task
UpdateAsync(T entity, bool IsCommit = true) { _Context.Set
().Attach(entity); _Context.Entry
(entity).State = EntityState.Modified; if (IsCommit) return await Task.Run(() => _Context.SaveChanges() > 0); else return await Task.Run(() => false); } ///
/// 增加或更新一条记录 /// ///
实体模型 ///
是否增加 ///
是否提交(默认提交) ///
public virtual bool SaveOrUpdate(T entity, bool IsSave, bool IsCommit = true) { return IsSave ? Save(entity, IsCommit) : Update(entity, IsCommit); } ///
/// 增加或更新一条记录(异步方式) /// ///
实体模型 ///
是否增加 ///
是否提交(默认提交) ///
public virtual async Task
SaveOrUpdateAsync(T entity, bool IsSave, bool IsCommit = true) { return IsSave ? await SaveAsync(entity, IsCommit) : await UpdateAsync(entity, IsCommit); } ///
/// 通过Lamda表达式获取实体 /// ///
Lamda表达式(p=>p.Id==Id) ///
public virtual T Get(Expression
> predicate) { return _Context.Set
().AsNoTracking().SingleOrDefault(predicate); } ///
/// 通过Lamda表达式获取实体(异步方式) /// ///
Lamda表达式(p=>p.Id==Id) ///
public virtual async Task
GetAsync(Expression
> predicate) { return await Task.Run(() => _Context.Set
().AsNoTracking().SingleOrDefault(predicate)); } ///
/// 删除一条记录 /// ///
实体模型 ///
是否提交(默认提交) ///
public virtual bool Delete(T entity, bool IsCommit = true) { if (entity == null) return false; _Context.Set
().Attach(entity); _Context.Set
().Remove(entity); if (IsCommit) return _Context.SaveChanges() > 0; else return false; } ///
/// 删除一条记录(异步方式) /// ///
实体模型 ///
是否提交(默认提交) ///
public virtual async Task
DeleteAsync(T entity, bool IsCommit = true) { if (entity == null) return await Task.Run(() => false); _Context.Set
().Attach(entity); _Context.Set
().Remove(entity); if (IsCommit) return await Task.Run(() => _Context.SaveChanges() > 0); else return await Task.Run(() => false); ; } #endregion #region 多模型 操作 ///
/// 增加多条记录,同一模型 /// ///
实体模型集合 ///
是否提交(默认提交) ///
public virtual bool SaveList(List
T1, bool IsCommit = true) { if (T1 == null || T1.Count == 0) return false; T1.ToList().ForEach(item => { _Context.Set
().Add(item); }); if (IsCommit) return _Context.SaveChanges() > 0; else return false; } ///
/// 增加多条记录,同一模型(异步方式) /// ///
实体模型集合 ///
是否提交(默认提交) ///
public virtual async Task
SaveListAsync(List
T1, bool IsCommit = true) { if (T1 == null || T1.Count == 0) return await Task.Run(() => false); T1.ToList().ForEach(item => { _Context.Set
().Add(item); }); if (IsCommit) return await Task.Run(() => _Context.SaveChanges() > 0); else return await Task.Run(() => false); } ///
/// 增加多条记录,独立模型 /// ///
实体模型集合 ///
是否提交(默认提交) ///
public virtual bool SaveList
(List
T, bool IsCommit = true) where T1 : class { if (T == null || T.Count == 0) return false; var tmp = _Context.ChangeTracker.Entries
().ToList(); foreach (var x in tmp) { var properties = typeof(T).GetTypeInfo().GetProperties(); foreach (var y in properties) { var entry = x.Property(y.Name); entry.CurrentValue = entry.OriginalValue; entry.IsModified = false; y.SetValue(x.Entity, entry.OriginalValue); } x.State = EntityState.Unchanged; } T.ToList().ForEach(item => { _Context.Set
().Add(item); }); if (IsCommit) return _Context.SaveChanges() > 0; else return false; } ///
/// 增加多条记录,独立模型(异步方式) /// ///
实体模型集合 ///
是否提交(默认提交) ///
public virtual async Task
SaveListAsync
(List
T, bool IsCommit = true) where T1 : class { if (T == null || T.Count == 0) return await Task.Run(() => false); var tmp = _Context.ChangeTracker.Entries
().ToList(); foreach (var x in tmp) { var properties = typeof(T).GetTypeInfo().GetProperties(); foreach (var y in properties) { var entry = x.Property(y.Name); entry.CurrentValue = entry.OriginalValue; entry.IsModified = false; y.SetValue(x.Entity, entry.OriginalValue); } x.State = EntityState.Unchanged; } T.ToList().ForEach(item => { _Context.Set
().Add(item); }); if (IsCommit) return await Task.Run(() => _Context.SaveChanges() > 0); else return await Task.Run(() => false); } ///
/// 更新多条记录,同一模型 /// ///
实体模型集合 ///
是否提交(默认提交) ///
public virtual bool UpdateList(List
T1, bool IsCommit = true) { if (T1 == null || T1.Count == 0) return false; T1.ToList().ForEach(item => { _Context.Set
().Attach(item); _Context.Entry
(item).State = EntityState.Modified; }); if (IsCommit) return _Context.SaveChanges() > 0; else return false; } ///
/// 更新多条记录,同一模型(异步方式) /// ///
实体模型集合 ///
是否提交(默认提交) ///
public virtual async Task
UpdateListAsync(List
T1, bool IsCommit = true) { if (T1 == null || T1.Count == 0) return await Task.Run(() => false); T1.ToList().ForEach(item => { _Context.Set
().Attach(item); _Context.Entry
(item).State = EntityState.Modified; }); if (IsCommit) return await Task.Run(() => _Context.SaveChanges() > 0); else return await Task.Run(() => false); } ///
/// 更新多条记录,独立模型 /// ///
实体模型集合 ///
是否提交(默认提交) ///
public virtual bool UpdateList
(List
T, bool IsCommit = true) where T1 : class { if (T == null || T.Count == 0) return false; T.ToList().ForEach(item => { _Context.Set
().Attach(item); _Context.Entry
(item).State = EntityState.Modified; }); if (IsCommit) return _Context.SaveChanges() > 0; else return false; } ///
/// 更新多条记录,独立模型(异步方式) /// ///
实体模型集合 ///
是否提交(默认提交) ///
public virtual async Task
UpdateListAsync
(List
T, bool IsCommit = true) where T1 : class { if (T == null || T.Count == 0) return await Task.Run(() => false); T.ToList().ForEach(item => { _Context.Set
().Attach(item); _Context.Entry
(item).State = EntityState.Modified; }); if (IsCommit) return await Task.Run(() => _Context.SaveChanges() > 0); else return await Task.Run(() => false); } ///
/// 删除多条记录,同一模型 /// ///
实体模型集合 ///
是否提交(默认提交) ///
public virtual bool DeleteList(List
T1, bool IsCommit = true) { if (T1 == null || T1.Count == 0) return false; T1.ToList().ForEach(item => { _Context.Set
().Attach(item); _Context.Set
().Remove(item); }); if (IsCommit) return _Context.SaveChanges() > 0; else return false; } ///
/// 删除多条记录,同一模型(异步方式) /// ///
实体模型集合 ///
是否提交(默认提交) ///
public virtual async Task
DeleteListAsync(List
T1, bool IsCommit = true) { if (T1 == null || T1.Count == 0) return await Task.Run(() => false); T1.ToList().ForEach(item => { _Context.Set
().Attach(item); _Context.Set
().Remove(item); }); if (IsCommit) return await Task.Run(() => _Context.SaveChanges() > 0); else return await Task.Run(() => false); } ///
/// 删除多条记录,独立模型 /// ///
实体模型集合 ///
是否提交(默认提交) ///
public virtual bool DeleteList
(List
T, bool IsCommit = true) where T1 : class { if (T == null || T.Count == 0) return false; T.ToList().ForEach(item => { _Context.Set
().Attach(item); _Context.Set
().Remove(item); }); if (IsCommit) return _Context.SaveChanges() > 0; else return false; } ///
/// 删除多条记录,独立模型(异步方式) /// ///
实体模型集合 ///
是否提交(默认提交) ///
public virtual async Task
DeleteListAsync
(List
T, bool IsCommit = true) where T1 : class { if (T == null || T.Count == 0) return await Task.Run(() => false); T.ToList().ForEach(item => { _Context.Set
().Attach(item); _Context.Set
().Remove(item); }); if (IsCommit) return await Task.Run(() => _Context.SaveChanges() > 0); else return await Task.Run(() => false); } ///
/// 通过Lamda表达式,删除一条或多条记录 /// ///
///
///
public virtual bool Delete(Expression
> predicate, bool IsCommit = true) { IQueryable
entry = (predicate == null) ? _Context.Set
().AsQueryable() : _Context.Set
().Where(predicate); List
list = entry.ToList(); if (list != null && list.Count == 0) return false; list.ForEach(item => { _Context.Set
().Attach(item); _Context.Set
().Remove(item); }); if (IsCommit) return _Context.SaveChanges() > 0; else return false; } ///
/// 通过Lamda表达式,删除一条或多条记录(异步方式) /// ///
///
///
public virtual async Task
DeleteAsync(Expression
> predicate, bool IsCommit = true) { IQueryable
entry = (predicate == null) ? _Context.Set
().AsQueryable() : _Context.Set
().Where(predicate); List
list = entry.ToList(); if (list != null && list.Count == 0) return await Task.Run(() => false); list.ForEach(item => { _Context.Set
().Attach(item); _Context.Set
().Remove(item); }); if (IsCommit) return await Task.Run(() => _Context.SaveChanges() > 0); else return await Task.Run(() => false); } #endregion #region 获取多条数据操作 ///
/// linq 分页 /// ///
///
条件 ///
排序 ///
页码 ///
每页条数 /// ///
查询字段 默认 为空 全部 ///
public virtual PagedynamicResult
GetLinqPage
(Expression
> whereQuery, QueryableOrderEntry
orderQuery, int pageID, int pageSizes) { // pageID = pageID < 1 ? 0 : pageID - 1; List
data = new List
(); var query = _Context.Set
().Where(whereQuery);// repository.TableNoTracking.Where(whereQuery); int count = query.Count(); //if (selector != null) //{ // if (orderQuery.OrderDirection == OrderDirection.DESC) // { // data = query.OrderByDescending(orderQuery.Expression).Select(selector) // .Skip(pageSizes * pageID) // .Take(pageSizes).ToList(); // } // else // { // data = query // .OrderBy(orderQuery.Expression).Select(selector) // .Skip(pageSizes * pageID) // .Take(pageSizes).ToList(); // } //} //else //{ if (orderQuery.OrderDirection == OrderDirection.DESC) { data = query.OrderByDescending(orderQuery.Expression) .Skip(pageSizes * pageID) .Take(pageSizes).ToList
(); } else { data = query .OrderBy(orderQuery.Expression) .Skip(pageSizes * pageID) .Take(pageSizes).ToList
(); } //} // var serviceProvider = _Context.GetInfrastructure
(); // var loggerFactory = serviceProvider.GetService
(); // loggerFactory.AddProvider(new MyLoggerProvider()); return new PagedynamicResult
{ Data = data, ItemCount = count, PageSize = pageSizes, PageIndex = pageID + 1 }; } ///
/// Lamda返回IQueryable集合,延时加载数据 /// ///
///
public virtual IQueryable
LoadAll(Expression
> predicate) { return predicate != null ? _Context.Set
().Where(predicate).AsNoTracking
() : _Context.Set
().AsQueryable
().AsNoTracking
(); } ///
/// 返回IQueryable集合,延时加载数据(异步方式) /// ///
///
public virtual async Task
> LoadAllAsync(Expression
> predicate) { return predicate != null ? await Task.Run(() => _Context.Set
().Where(predicate).AsNoTracking
()) : await Task.Run(() => _Context.Set
().AsQueryable
().AsNoTracking
()); } ///
/// 返回List
集合,不采用延时加载 ///
///
///
public virtual List
LoadListAll(Expression
> predicate) { return predicate != null ? _Context.Set
().Where(predicate).AsNoTracking().ToList() : _Context.Set
().AsQueryable
().AsNoTracking().ToList(); } //
/// 返回List
集合,不采用延时加载(异步方式) ///
///
///
public virtual async Task
> LoadListAllAsync(Expression
> predicate) { return predicate != null ? await Task.Run(() => _Context.Set
().Where(predicate).AsNoTracking().ToList()) : await Task.Run(() => _Context.Set
().AsQueryable
().AsNoTracking().ToList()); } ///
/// T-Sql方式:返回IQueryable
集合 ///
///
SQL语句 ///
Parameters参数 ///
public virtual IQueryable
LoadAllBySql(string sql, params DbParameter[] para) { return _Context.Set
().FromSql(sql, para); } ///
/// T-Sql方式:返回IQueryable
集合(异步方式) ///
///
SQL语句 ///
Parameters参数 ///
public virtual async Task
> LoadAllBySqlAsync(string sql, params DbParameter[] para) { return await Task.Run(() => _Context.Set
().FromSql(sql, para)); } ///
/// T-Sql方式:返回List
集合 ///
///
SQL语句 ///
Parameters参数 ///
public virtual List
LoadListAllBySql(string sql, params DbParameter[] para) { return _Context.Set
().FromSql(sql, para).Cast
().ToList(); } ///
/// T-Sql方式:返回List
集合(异步方式) ///
///
SQL语句 ///
Parameters参数 ///
public virtual async Task
> LoadListAllBySqlAsync(string sql, params DbParameter[] para) { return await Task.Run(() => _Context.Set
().FromSql(sql, para).Cast
().ToList()); } ///
/// 可指定返回结果、排序、查询条件的通用查询方法,返回实体对象集合 /// ///
实体对象
///
排序字段类型
///
数据结果,与TEntity一致
///
过滤条件,需要用到类型转换的需要提前处理与数据表一致的 ///
排序字段 ///
返回结果(必须是模型中存在的字段) ///
排序方向,true为正序false为倒序 ///
实体集合
//public virtual List
QueryEntity
// (Expression
> where, // Expression
> orderby, // Expression
> selector, // bool IsAsc) // where TEntity : class // where TResult : class //{ // IQueryable
query = _Context.Set
(); // if (where != null) // { // query = query.Where(where); // } // if (orderby != null) // { // query = IsAsc ? query.OrderBy(orderby) : query.OrderByDescending(orderby); // } // if (selector == null) // { // return query.Cast
().AsNoTracking().ToList(); // } // return query.Select(selector).AsNoTracking().ToList(); //} ///
/// 可指定返回结果、排序、查询条件的通用查询方法,返回实体对象集合(异步方式) /// ///
实体对象
///
排序字段类型
///
数据结果,与TEntity一致
///
过滤条件,需要用到类型转换的需要提前处理与数据表一致的 ///
排序字段 ///
返回结果(必须是模型中存在的字段) ///
排序方向,true为正序false为倒序 ///
实体集合
//public virtual async Task
> QueryEntityAsync
// (Expression
> where, // Expression
> orderby, // Expression
> selector, // bool IsAsc) // where TEntity : class // where TResult : class //{ // IQueryable
query = _Context.Set
(); // if (where != null) // { // query = query.Where(where); // } // if (orderby != null) // { // query = IsAsc ? query.OrderBy(orderby) : query.OrderByDescending(orderby); // } // if (selector == null) // { // return await Task.Run(() => query.Cast
().AsNoTracking().ToList()); // } // return await Task.Run(() => query.Select(selector).AsNoTracking().ToList()); //} ///
/// 可指定返回结果、排序、查询条件的通用查询方法,返回Object对象集合 /// ///
实体对象
///
排序字段类型
///
过滤条件,需要用到类型转换的需要提前处理与数据表一致的 ///
排序字段 ///
返回结果(必须是模型中存在的字段) ///
排序方向,true为正序false为倒序 ///
自定义实体集合
//public virtual List
QueryObject
// (Expression
> where, // Expression
> orderby, // Func
, // List
> selector, // bool IsAsc) // where TEntity : class //{ // IQueryable
query = _Context.Set
(); // if (where != null) // { // query = query.Where(where); // } // if (orderby != null) // { // query = IsAsc ? query.OrderBy(orderby) : query.OrderByDescending(orderby); // } // if (selector == null) // { // return query.AsNoTracking().ToList
(); // } // return selector(query); //} /// /// 可指定返回结果、排序、查询条件的通用查询方法,返回Object对象集合(异步方式) /// ///
实体对象
///
排序字段类型
/// 过滤条件,需要用到类型转换的需要提前处理与数据表一致的 /// 排序字段 /// 返回结果(必须是模型中存在的字段) /// 排序方向,true为正序false为倒序 ///
自定义实体集合
//public virtual async Task
> QueryObjectAsync
// (Expression
> where, // Expression
> orderby, // Func
, // List
> selector, // bool IsAsc) // where TEntity : class //{ // IQueryable
query = _Context.Set
(); // if (where != null) // { // query = query.Where(where); // } // if (orderby != null) // { // query = IsAsc ? query.OrderBy(orderby) : query.OrderByDescending(orderby); // } // if (selector == null) // { // return await Task.Run(() => query.AsNoTracking().ToList
()); // } // return await Task.Run(() => selector(query)); //} /// /// 可指定返回结果、排序、查询条件的通用查询方法,返回动态类对象集合 /// ///
实体对象
///
排序字段类型
/// 过滤条件,需要用到类型转换的需要提前处理与数据表一致的 /// 排序字段 /// 返回结果(必须是模型中存在的字段) /// 排序方向,true为正序false为倒序 ///
动态类
//public virtual dynamic QueryDynamic
// (Expression
> where, // Expression
> orderby, // Func
, // List
> selector, // bool IsAsc) // where TEntity : class //{ // List list = QueryObject
// (where, orderby, selector, IsAsc); // return Common.JsonHelper.JsonConvert.JsonClass(list); //} ///
/// 可指定返回结果、排序、查询条件的通用查询方法,返回动态类对象集合(异步方式) /// ///
实体对象
///
排序字段类型
///
过滤条件,需要用到类型转换的需要提前处理与数据表一致的 ///
排序字段 ///
返回结果(必须是模型中存在的字段) ///
排序方向,true为正序false为倒序 ///
动态类
//public virtual async Task
QueryDynamicAsync
// (Expression
> where, // Expression
> orderby, // Func
, // List
> selector, // bool IsAsc) // where TEntity : class //{ // List list = QueryObject
// (where, orderby, selector, IsAsc); // return await Task.Run(() => Common.JsonHelper.JsonConvert.JsonClass(list)); //} #endregion #region 验证是否存在 ///
/// 验证当前条件是否存在相同项 /// public virtual bool IsExist(Expression
> predicate) { var entry = _Context.Set
().Where(predicate); return (entry.Any()); } ///
/// 验证当前条件是否存在相同项(异步方式) /// public virtual async Task
IsExistAsync(Expression
> predicate) { var entry = _Context.Set
().Where(predicate); return await Task.Run(() => entry.Any()); } ///
/// 根据SQL验证实体对象是否存在 /// public virtual bool IsExist(string sql, params DbParameter[] para) { return _Context.Database.ExecuteSqlCommand(sql, para) > 0; } ///
/// 根据SQL验证实体对象是否存在(异步方式) /// public virtual async Task
IsExistAsync(string sql, params DbParameter[] para) { return await Task.Run(() => _Context.Database.ExecuteSqlCommand(sql, para) > 0); } #endregion }}

  

using System;using System.Collections.Generic;using System.Text;namespace efcore.Repository{    ///     /// Describe:工作单元实现类    /// Author:yuangang    /// Date:2016/07/16    /// Blogs:http://www.cnblogs.com/yuangang    ///     public class UnitOfWork : IUnitOfWork, IDisposable    {        #region 数据上下文        ///         /// 数据上下文        ///         private ApplicationDbContext _Context;        public UnitOfWork(ApplicationDbContext Context)        {            _Context = Context;        }        #endregion             public bool Commit()        {            return _Context.SaveChanges() > 0;        }        public void Dispose()        {            if (_Context != null)            {                _Context.Dispose();            }            GC.SuppressFinalize(this);        }    }}

  

using Microsoft.EntityFrameworkCore;using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Linq.Expressions;using System.Reflection;using System.Data.Common;using Microsoft.Extensions.Logging;namespace efcore.Repository{    public class ApplicationDbContext : DbContext    {       // private readonly ILogger _logger;        private readonly ILoggerFactory _logger;        public ApplicationDbContext(ILoggerFactory _loggerFactory, DbContextOptions
options) : base(options) { // var fff= base.Database.ToString(); // options. ProviderManifestToken // _logger = _loggerFactory.CreateLogger
(); _logger = _loggerFactory ; } public DbSet
SYS_USER { get; set; } public DbSet
tt { get; set; } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseLoggerFactory(_logger); } } //#region DbCommandInterceptor拦截生成的SQL语句 //class EFIntercepterLogging : DbCommandInterceptor //{ // private readonly Stopwatch _stopwatch = new Stopwatch(); // public override void ScalarExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext interceptionContext) // { // base.ScalarExecuting(command, interceptionContext); // _stopwatch.Restart(); // } // public override void ScalarExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext interceptionContext) // { // _stopwatch.Stop(); // if (interceptionContext.Exception != null) // { // Trace.TraceError("Exception:{1} \r\n --> Error executing command: {0}", command.CommandText, interceptionContext.Exception.ToString()); // } // else // { // Trace.TraceInformation("\r\n执行时间:{0} 毫秒\r\n-->ScalarExecuted.Command:{1}\r\n", _stopwatch.ElapsedMilliseconds, command.CommandText); // } // base.ScalarExecuted(command, interceptionContext); // } // public override void NonQueryExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext
interceptionContext) // { // base.NonQueryExecuting(command, interceptionContext); // _stopwatch.Restart(); // } // public override void NonQueryExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext
interceptionContext) // { // _stopwatch.Stop(); // if (interceptionContext.Exception != null) // { // Trace.TraceError("Exception:{1} \r\n --> Error executing command:\r\n {0}", command.CommandText, interceptionContext.Exception.ToString()); // } // else // { // Trace.TraceInformation("\r\n执行时间:{0} 毫秒\r\n-->NonQueryExecuted.Command:\r\n{1}", _stopwatch.ElapsedMilliseconds, command.CommandText); // } // base.NonQueryExecuted(command, interceptionContext); // } // public override void ReaderExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext
interceptionContext) // { // base.ReaderExecuting(command, interceptionContext); // _stopwatch.Restart(); // } // public override void ReaderExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext
interceptionContext) // { // _stopwatch.Stop(); // if (interceptionContext.Exception != null) // { // Trace.TraceError("Exception:{1} \r\n --> Error executing command:\r\n {0}", command.CommandText, interceptionContext.Exception.ToString()); // } // else // { // Trace.TraceInformation("\r\n执行时间:{0} 毫秒 \r\n -->ReaderExecuted.Command:\r\n{1}", _stopwatch.ElapsedMilliseconds, command.CommandText); // } // base.ReaderExecuted(command, interceptionContext); // } //} //#endregion public class PagedynamicResult
{ public int ItemCount { get; set; } public int PageIndex { get; set; } public int PageSize { get; set; } public int PageCount { get { try { int m = ItemCount % PageSize; if (m == 0) return ItemCount / PageSize; else return ItemCount / PageSize + 1; } catch { return 0; } } } public List
Data { get; set; } } ///
/// 分页返回数据 /// ///
public class PageResult
{ public int ItemCount { get; set; } public int PageIndex { get; set; } public int PageSize { get; set; } public int PageCount { get { try { int m = ItemCount % PageSize; if (m == 0) return ItemCount / PageSize; else return ItemCount / PageSize + 1; } catch { return 0; } } } public List
Data { get; set; } } #region 查询条件扩展 public static class PredicateBuilder { ///
/// Convert a lambda expression for a getter into a setter /// public static Action
GetSetter
(Expression
> expression) { var memberExpression = (MemberExpression)expression.Body; var property = (PropertyInfo)memberExpression.Member; var setMethod = property.GetSetMethod(); var parameterT = Expression.Parameter(typeof(T), "x"); var parameterTProperty = Expression.Parameter(typeof(TProperty), "y"); var newExpression = Expression.Lambda
>( Expression.Call(parameterT, setMethod, parameterTProperty), parameterT, parameterTProperty ); return newExpression.Compile(); } public static Expression
> True
() { return f => true; } public static Expression
> False
() { return f => false; } public static Expression
Compose
(this Expression
first, Expression
second, Func
merge) { // build parameter map (from parameters of second to parameters of first) var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f); // replace parameters in the second lambda expression with parameters from the first var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); // apply composition of lambda expression bodies to parameters from the first expression return Expression.Lambda
(merge(first.Body, secondBody), first.Parameters); } public static Expression
> And
(this Expression
> first, Expression
> second) { return first.Compose(second, Expression.And); } public static Expression
> Or
(this Expression
> first, Expression
> second) { return first.Compose(second, Expression.Or); } } public class ParameterRebinder : ExpressionVisitor { private readonly Dictionary
map; public ParameterRebinder(Dictionary
map) { this.map = map ?? new Dictionary
(); } public static Expression ReplaceParameters(Dictionary
map, Expression exp) { return new ParameterRebinder(map).Visit(exp); } protected override Expression VisitParameter(ParameterExpression p) { ParameterExpression replacement; if (map.TryGetValue(p, out replacement)) { p = replacement; } return base.VisitParameter(p); } } #endregion #region 排序扩展 public class QueryableOrderEntry
{ public QueryableOrderEntry(Expression
> expression) { this.Expression = expression; OrderDirection = OrderDirection.ASC; } public QueryableOrderEntry(Expression
> expression, OrderDirection orderDirection) { this.Expression = expression; OrderDirection = orderDirection; } public Expression
> Expression { get; set; } public OrderDirection OrderDirection { get; set; } } public enum OrderDirection { ASC, DESC } #endregion}

  

services.AddDbContext
(options => options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection"), b => b.UseRowNumberForPaging()));

  

你可能感兴趣的文章
原生态Ajax(转)
查看>>
页面间对象传递的方法
查看>>
解决Ajax跨域问题:Origin xx is not allowed by Access-Control-Allow-Origin.
查看>>
js闭包
查看>>
Java编程小技巧集锦
查看>>
Codeforces 856C - Eleventh Birthday
查看>>
数字梯形问题
查看>>
Javascript 操作select控件大全(新增、修改、删除、选中、清空、判断存在等)...
查看>>
完全数据库脱机备份+完全数据库脱机备份案列
查看>>
New Concept English there (9)
查看>>
ES6——块级作用域
查看>>
6-SUPER关键字
查看>>
行动力决定你的水准
查看>>
python之生产者消费者模型
查看>>
linux rsync同步工具
查看>>
Linux中的特殊权限s、t、i、a
查看>>
轻院1066: 字符分类统计
查看>>
windows上 nginx 配置代理服务,配置多域名,以及最简单实现跨域配置
查看>>
VS界面控件大小调整
查看>>
POJ1066:Treasure Hunt——题解
查看>>