/// <summary>
/// SqlSugar 注入Service的扩展方法
/// </summary>
public static class SqlSugarServiceCollectionExtensions
{
/// <summary>
/// SqlSugar上下文注入
/// </summary>
/// <typeparam name="TSugarContext">要注册的上下文的类型</typeparam>
/// <param name="serviceCollection"></param>
/// <param name="configAction"></param>
/// <param name="lifetime">用于在容器中注册TSugarClient服务的生命周期</param>
/// <returns></returns>
public static IServiceCollection AddSqlSugarClient<TSugarContext>(this IServiceCollection serviceCollection, Action<IServiceProvider, ConnectionConfig> configAction, ServiceLifetime lifetime = ServiceLifetime.Singleton)
where TSugarContext : IDbFactory
{
serviceCollection.AddMemoryCache().AddLogging();
serviceCollection.TryAdd(new ServiceDescriptor(typeof(ConnectionConfig), p => ConnectionConfigFactory(p, configAction), lifetime));
serviceCollection.Add(new ServiceDescriptor(typeof(ConnectionConfig), p => ConnectionConfigFactory(p, configAction), lifetime));
serviceCollection.TryAdd(new ServiceDescriptor(typeof(TSugarContext), typeof(TSugarContext), lifetime));
return serviceCollection;
} private static ConnectionConfig ConnectionConfigFactory(IServiceProvider applicationServiceProvider, Action<IServiceProvider, ConnectionConfig> configAction)
{
var config = new ConnectionConfig();
configAction.Invoke(applicationServiceProvider, config);
return config;
}
}

注入扩展

 public interface IDbFactory
{
SqlSugarClient GetDbContext(Action<Exception> onErrorEvent);
SqlSugarClient GetDbContext(Action<string, SugarParameter[]> onExecutedEvent);
SqlSugarClient GetDbContext(Func<string, SugarParameter[], KeyValuePair<string, SugarParameter[]>> onExecutingChangeSqlEvent);
SqlSugarClient GetDbContext(Action<string, SugarParameter[]> onExecutedEvent = null, Func<string, SugarParameter[], KeyValuePair<string, SugarParameter[]>> onExecutingChangeSqlEvent = null, Action<Exception> onErrorEvent = null);
}

IDbFactory

 public class DbFactory : IDbFactory
{
private readonly ILogger _logger;
private readonly ConnectionConfig _config; public DbFactory(ConnectionConfig config, ILogger<DbFactory> logger)
{
this._logger = logger;
this._config = config;
} public SqlSugarClient GetDbContext(Action<Exception> onErrorEvent) => GetDbContext(null, null, onErrorEvent);
public SqlSugarClient GetDbContext(Action<string, SugarParameter[]> onExecutedEvent) => GetDbContext(onExecutedEvent);
public SqlSugarClient GetDbContext(Func<string, SugarParameter[], KeyValuePair<string, SugarParameter[]>> onExecutingChangeSqlEvent) => GetDbContext(null, onExecutingChangeSqlEvent);
public SqlSugarClient GetDbContext(Action<string, SugarParameter[]> onExecutedEvent = null, Func<string, SugarParameter[], KeyValuePair<string, SugarParameter[]>> onExecutingChangeSqlEvent = null, Action<Exception> onErrorEvent = null)
{
SqlSugarClient db = new SqlSugarClient(_config)
{
Aop =
{
OnExecutingChangeSql = onExecutingChangeSqlEvent,
OnError = onErrorEvent ?? ((Exception ex) => { this._logger.LogError(ex, "ExecuteSql Error"); }),
OnLogExecuted =onExecutedEvent?? ((string sql, SugarParameter[] pars) =>
{
var keyDic = new KeyValuePair<string, SugarParameter[]>(sql, pars);
this._logger.LogInformation($"ExecuteSql:【{keyDic.ToJson()}】");
})
}
};
return db;
}
}

DbFactory

    public interface IRepository
{ }

IRepository

  public class Repository<TFactory, TIRepository> : IRepository where TFactory : IDbFactory where TIRepository : IRepository
{
protected readonly ILogger Log;
protected readonly TFactory Factory;
protected readonly TIRepository DbRepository;
protected SqlSugarClient DbContext => this.Factory.GetDbContext(); public Repository(TFactory factory) => Factory = factory;
public Repository(TFactory factory, ILogger logger) : this(factory) => Log = logger;
public Repository(TFactory factory, TIRepository repository) : this(factory) => DbRepository = repository;
public Repository(TFactory factory, TIRepository repository, ILogger logger) : this(factory, repository) => Log = logger;
} public class Repository<TFactory> : IRepository where TFactory : IDbFactory
{
protected readonly ILogger Log;
protected readonly TFactory Factory;
protected SqlSugarClient DbContext => this.Factory.GetDbContext(); public Repository(TFactory factory) => Factory = factory;
public Repository(TFactory factory, ILogger logger) : this(factory) => Log = logger;
}

Repository

   public static class SugarFactoryExtensions
{ #region 根据主键获取实体对象 /// <summary>
/// 根据主键获取实体对象
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <param name="db"></param>
/// <param name="id"></param>
/// <returns></returns>
public static TSource GetById<TSource>(this SqlSugarClient db, dynamic id) where TSource : EntityBase, new()
{
return db.Queryable<TSource>().InSingle(id);
} /// <summary>
/// 根据主键获取实体对象
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <typeparam name="TMap">数据源映射类型</typeparam>
/// <param name="db"></param>
/// <param name="id"></param>
/// <returns></returns>
public static TMap GetById<TSource, TMap>(this SqlSugarClient db, dynamic id) where TSource : EntityBase, new()
{
TSource model = db.Queryable<TSource>().InSingle(id);
return model.Map<TSource, TMap>();
} #endregion #region 根据Linq表达式条件获取单个实体对象 /// <summary>
/// 根据条件获取单个实体对象
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <param name="db"></param>
/// <param name="whereExp"></param>
/// <returns></returns>
public static TSource Get<TSource>(this SqlSugarClient db, Expression<Func<TSource, bool>> whereExp) where TSource : EntityBase, new()
{
return db.Queryable<TSource>().Where(whereExp).Single();
} /// <summary>
/// 根据条件获取单个实体对象
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <typeparam name="TMap">数据源映射类型</typeparam>
/// <param name="db"></param>
/// <param name="whereExp">条件表达式</param>
/// <returns></returns>
public static TMap Get<TSource, TMap>(this SqlSugarClient db, Expression<Func<TSource, bool>> whereExp) where TSource : EntityBase, new()
{
TSource model = db.Queryable<TSource>().Where(whereExp).Single();
return model.Map<TSource, TMap>();
} #endregion #region 获取所有实体列表 /// <summary>
/// 获取所有实体列表
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <param name="db"></param>
/// <returns></returns>
public static List<TSource> GetList<TSource>(this SqlSugarClient db) where TSource : EntityBase, new()
{
return db.Queryable<TSource>().ToList();
} /// <summary>
/// 获取实体列表
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <typeparam name="TMap">数据源映射类型</typeparam>
/// <param name="db"></param>
/// <returns></returns>
public static List<TMap> GetList<TSource, TMap>(this SqlSugarClient db) where TSource : EntityBase, new()
{
var result = db.Queryable<TSource>().ToList();
return result.Map<List<TSource>, List<TMap>>();
} #endregion #region 根据Linq表达式条件获取列表 /// <summary>
/// 根据条件获取实体列表
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <param name="db"></param>
/// <param name="whereExp">条件表达式</param>
/// <returns></returns>
public static List<TSource> GetList<TSource>(this SqlSugarClient db, Expression<Func<TSource, bool>> whereExp) where TSource : EntityBase, new()
{
return db.Queryable<TSource>().Where(whereExp).ToList();
} /// <summary>
/// 根据条件获取实体列表
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <typeparam name="TMap">数据源映射类型</typeparam>
/// <param name="db"></param>
/// <param name="whereExp">条件表达式</param>
/// <returns></returns>
public static List<TMap> GetList<TSource, TMap>(this SqlSugarClient db, Expression<Func<TSource, bool>> whereExp) where TSource : EntityBase, new()
{
var result = db.Queryable<TSource>().Where(whereExp).ToList();
return result.Map<List<TSource>, List<TMap>>();
} #endregion #region 根据Sugar条件获取列表 /// <summary>
/// 根据条件获取实体列表
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="db"></param>
/// <param name="conditionals">Sugar调价表达式集合</param>
/// <returns></returns>
public static List<TSource> GetList<TSource>(this SqlSugarClient db, List<IConditionalModel> conditionals) where TSource : EntityBase, new()
{
return db.Queryable<TSource>().Where(conditionals).ToList();
} /// <summary>
/// 根据条件获取实体列表
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <typeparam name="TMap">数据源映射类型</typeparam>
/// <param name="db"></param>
/// <param name="conditionals">Sugar调价表达式集合</param>
/// <returns></returns>
public static List<TMap> GetList<TSource, TMap>(this SqlSugarClient db, List<IConditionalModel> conditionals) where TSource : EntityBase, new()
{
var result = db.Queryable<TSource>().Where(conditionals).ToList();
return result.Map<List<TSource>, List<TMap>>();
} #endregion #region 是否包含某个元素
/// <summary>
/// 是否包含某个元素
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="db"></param>
/// <param name="whereExp">条件表达式</param>
/// <returns></returns>
public static bool Exist<TSource>(this SqlSugarClient db, Expression<Func<TSource, bool>> whereExp) where TSource : EntityBase, new()
{
return db.Queryable<TSource>().Where(whereExp).Any();
}
#endregion #region 新增实体对象
/// <summary>
/// 新增实体对象
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="db"></param>
/// <param name="insertObj"></param>
/// <returns></returns>
public static bool Insert<TSource>(this SqlSugarClient db, TSource insertObj) where TSource : EntityBase, new()
{
return db.Insertable(insertObj).ExecuteCommand() > ;
} /// <summary>
/// 新增实体对象
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TMap"></typeparam>
/// <param name="db"></param>
/// <param name="insertDto"></param>
/// <returns></returns>
public static bool Insert<TSource, TMap>(this SqlSugarClient db, TSource insertDto) where TMap : EntityBase, new()
{
var entity = insertDto.Map<TSource, TMap>();
return db.Insertable(entity).ExecuteCommand() > ;
}
#endregion #region 批量新增实体对象
/// <summary>
/// 批量新增实体对象
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="db"></param>
/// <param name="insertObjs"></param>
/// <returns></returns>
public static bool InsertRange<TSource>(this SqlSugarClient db, List<TSource> insertObjs) where TSource : EntityBase, new()
{
return db.Insertable(insertObjs).ExecuteCommand() > ;
} /// <summary>
/// 批量新增实体对象
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TMap"></typeparam>
/// <param name="db"></param>
/// <param name="insertObjs"></param>
/// <returns></returns>
public static bool InsertRange<TSource, TMap>(this SqlSugarClient db, List<TSource> insertObjs) where TMap : EntityBase, new()
{
var entitys = insertObjs.Map<List<TSource>, List<TMap>>();
return db.Insertable(entitys).ExecuteCommand() > ;
}
#endregion #region 更新单个实体对象
/// <summary>
/// 更新单个实体对象
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="db"></param>
/// <param name="updateObj"></param>
/// <returns></returns>
public static bool Update<TSource>(this SqlSugarClient db, TSource updateObj) where TSource : EntityBase, new()
{
return db.Updateable(updateObj).ExecuteCommand() > ;
}
#endregion #region 根据条件批量更新实体指定列
/// <summary>
/// 根据条件批量更新实体指定列
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="db"></param>
/// <param name="columns">需要更新的列</param>
/// <param name="whereExp">条件表达式</param>
/// <returns></returns>
public static bool Update<TSource>(this SqlSugarClient db, Expression<Func<TSource, TSource>> columns, Expression<Func<TSource, bool>> whereExp) where TSource : EntityBase, new()
{
return db.Updateable<TSource>().UpdateColumns(columns).Where(whereExp).ExecuteCommand() > ;
}
#endregion #region 物理删除实体对象 /// <summary>
/// 物理删除实体对象
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="db"></param>
/// <param name="deleteObj"></param>
/// <returns></returns>
public static bool Delete<TSource>(this SqlSugarClient db, TSource deleteObj) where TSource : EntityBase, new()
{
return db.Deleteable<TSource>().Where(deleteObj).ExecuteCommand() > ;
} /// <summary>
/// 物理删除实体对象
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="db"></param>
/// <param name="whereExp">条件表达式</param>
/// <returns></returns>
public static bool Delete<TSource>(this SqlSugarClient db, Expression<Func<TSource, bool>> whereExp) where TSource : EntityBase, new()
{
return db.Deleteable<TSource>().Where(whereExp).ExecuteCommand() > ;
} /// <summary>
/// 根据主键物理删除实体对象
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="db"></param>
/// <param name="id"></param>
/// <returns></returns>
public static bool DeleteById<TSource>(this SqlSugarClient db, dynamic id) where TSource : EntityBase, new()
{
return db.Deleteable<TSource>().In(id).ExecuteCommand() > ;
} /// <summary>
/// 根据主键批量物理删除实体集合
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="db"></param>
/// <param name="ids"></param>
/// <returns></returns>
public static bool DeleteByIds<TSource>(this SqlSugarClient db, dynamic[] ids) where TSource : EntityBase, new()
{
return db.Deleteable<TSource>().In(ids).ExecuteCommand() > ;
} #endregion #region 分页查询 /// <summary>
/// 获取分页列表【页码,每页条数】
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <param name="db"></param>
/// <param name="pageIndex">页码(从0开始)</param>
/// <param name="pageSize">每页条数</param>
/// <returns></returns>
public static IPagedList<TSource> GetPageList<TSource>(this SqlSugarClient db, int pageIndex, int pageSize) where TSource : EntityBase, new()
{
int count = ;
var result = db.Queryable<TSource>().ToPageList(pageIndex, pageSize, ref count);
return new PagedList<TSource>(result, pageIndex, pageSize, count);
} /// <summary>
/// 获取分页列表【页码,每页条数】
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <typeparam name="TMap">数据源映射类型</typeparam>
/// <param name="db"></param>
/// <param name="pageIndex">页码(从0开始)</param>
/// <param name="pageSize">每页条数</param>
/// <returns></returns>
public static IPagedList<TMap> GetPageList<TSource, TMap>(this SqlSugarClient db, int pageIndex, int pageSize) where TSource : EntityBase, new()
{
int count = ;
var result = db.Queryable<TSource>().ToPageList(pageIndex, pageSize, ref count);
var pageResult = new PagedList<TSource>(result, pageIndex, pageSize, count);
return pageResult.Map<TSource, TMap>();
} #endregion #region 分页查询(排序) /// <summary>
/// 获取分页列表【排序,页码,每页条数】
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <param name="db"></param>
/// <param name="orderExp">排序表达式</param>
/// <param name="orderType">排序类型</param>
/// <param name="pageIndex">页码(从0开始)</param>
/// <param name="pageSize">每页条数</param>
/// <returns></returns>
public static IPagedList<TSource> GetPageList<TSource>(this SqlSugarClient db, Expression<Func<TSource, object>> orderExp, OrderByType orderType, int pageIndex, int pageSize) where TSource : EntityBase, new()
{
int count = ;
var result = db.Queryable<TSource>().OrderBy(orderExp, orderType).ToPageList(pageIndex, pageSize, ref count);
return new PagedList<TSource>(result, pageIndex, pageSize, count);
} /// <summary>
/// 获取分页列表【排序,页码,每页条数】
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <typeparam name="TMap">数据源映射类型</typeparam>
/// <param name="db"></param>
/// <param name="orderExp">排序表达式</param>
/// <param name="orderType">排序类型</param>
/// <param name="pageIndex">页码(从0开始)</param>
/// <param name="pageSize">每页条数</param>
/// <returns></returns>
public static IPagedList<TMap> GetPageList<TSource, TMap>(this SqlSugarClient db, Expression<Func<TSource, object>> orderExp, OrderByType orderType, int pageIndex, int pageSize) where TSource : EntityBase, new()
{
int count = ;
var result = db.Queryable<TSource>().OrderBy(orderExp, orderType).ToPageList(pageIndex, pageSize, ref count);
var pageResult = new PagedList<TSource>(result, pageIndex, pageSize, count);
return pageResult.Map<TSource, TMap>();
} #endregion #region 分页查询(Linq表达式条件) /// <summary>
/// 获取分页列表【Linq表达式条件,页码,每页条数】
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <param name="db"></param>
/// <param name="whereExp">Linq表达式条件</param>
/// <param name="pageIndex">页码(从0开始)</param>
/// <param name="pageSize">每页条数</param>
/// <returns></returns>
public static IPagedList<TSource> GetPageList<TSource>(this SqlSugarClient db, Expression<Func<TSource, bool>> whereExp, int pageIndex, int pageSize) where TSource : EntityBase, new()
{
int count = ;
var result = db.Queryable<TSource>().Where(whereExp).ToPageList(pageIndex, pageSize, ref count);
return new PagedList<TSource>(result, pageIndex, pageSize, count);
} /// <summary>
/// 获取分页列表【Linq表达式条件,页码,每页条数】
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <typeparam name="TMap">数据源映射类型</typeparam>
/// <param name="db"></param>
/// <param name="whereExp">Linq表达式条件</param>
/// <param name="pageIndex">页码(从0开始)</param>
/// <param name="pageSize">每页条数</param>
/// <returns></returns>
public static IPagedList<TMap> GetPageList<TSource, TMap>(this SqlSugarClient db, Expression<Func<TSource, bool>> whereExp, int pageIndex, int pageSize) where TSource : EntityBase, new()
{
int count = ;
var result = db.Queryable<TSource>().Where(whereExp).ToPageList(pageIndex, pageSize, ref count);
var pageResult = new PagedList<TSource>(result, pageIndex, pageSize, count);
return pageResult.Map<TSource, TMap>();
} #endregion #region 分页查询(Linq表达式条件,排序) /// <summary>
/// 获取分页列表【Linq表达式条件,排序,页码,每页条数】
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <param name="db"></param>
/// <param name="whereExp">Linq表达式条件</param>
/// <param name="orderExp">排序表达式</param>
/// <param name="orderType">排序类型</param>
/// <param name="pageIndex">页码(从0开始)</param>
/// <param name="pageSize">每页条数</param>
/// <returns></returns>
public static IPagedList<TSource> GetPageList<TSource>(this SqlSugarClient db, Expression<Func<TSource, bool>> whereExp, Expression<Func<TSource, object>> orderExp, OrderByType orderType, int pageIndex, int pageSize) where TSource : EntityBase, new()
{
int count = ;
var result = db.Queryable<TSource>().Where(whereExp).OrderBy(orderExp, orderType).ToPageList(pageIndex, pageSize, ref count);
return new PagedList<TSource>(result, pageIndex, pageSize, count);
} /// <summary>
/// 获取分页列表【Linq表达式条件,排序,页码,每页条数】
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <typeparam name="TMap">数据源映射类型</typeparam>
/// <param name="db"></param>
/// <param name="whereExp">Linq表达式条件</param>
/// <param name="orderExp">排序表达式</param>
/// <param name="orderType">排序类型</param>
/// <param name="pageIndex">页码(从0开始)</param>
/// <param name="pageSize">每页条数</param>
/// <returns></returns>
public static IPagedList<TMap> GetPageList<TSource, TMap>(this SqlSugarClient db, Expression<Func<TSource, bool>> whereExp, Expression<Func<TSource, object>> orderExp, OrderByType orderType, int pageIndex, int pageSize) where TSource : EntityBase, new()
{
int count = ;
var result = db.Queryable<TSource>().Where(whereExp).OrderBy(orderExp, orderType).ToPageList(pageIndex, pageSize, ref count);
var pageResult = new PagedList<TSource>(result, pageIndex, pageSize, count);
return pageResult.Map<TSource, TMap>();
} #endregion #region 分页查询(Sugar条件) /// <summary>
/// 获取分页列表【Sugar表达式条件,页码,每页条数】
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <param name="db"></param>
/// <param name="conditionals">Sugar条件表达式集合</param>
/// <param name="pageIndex">页码(从0开始)</param>
/// <param name="pageSize">每页条数</param>
/// <returns></returns>
public static IPagedList<TSource> GetPageList<TSource>(this SqlSugarClient db, List<IConditionalModel> conditionals, int pageIndex, int pageSize) where TSource : EntityBase, new()
{
int count = ;
var result = db.Queryable<TSource>().Where(conditionals).ToPageList(pageIndex, pageSize, ref count);
return new PagedList<TSource>(result, pageIndex, pageSize, count);
} /// <summary>
/// 获取分页列表【Sugar表达式条件,页码,每页条数】
/// </summary>
/// <typeparam name="TSource">数据源类型</typeparam>
/// <typeparam name="TMap">数据源映射类型</typeparam>
/// <param name="db"></param>
/// <param name="conditionals">Sugar条件表达式集合</param>
/// <param name="pageIndex">页码(从0开始)</param>
/// <param name="pageSize">每页条数</param>
/// <returns></returns>
public static IPagedList<TMap> GetPageList<TSource, TMap>(this SqlSugarClient db, List<IConditionalModel> conditionals, int pageIndex, int pageSize) where TSource : EntityBase, new()
{
int count = ;
var result = db.Queryable<TSource>().Where(conditionals).ToPageList(pageIndex, pageSize, ref count);
var pageResult = new PagedList<TSource>(result, pageIndex, pageSize, count);
return pageResult.Map<TSource, TMap>();
} #endregion #region 分页查询(Sugar条件,排序) /// <summary>
/// 获取分页列表【Sugar表达式条件,排序,页码,每页条数】
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="db"></param>
/// <param name="conditionals">Sugar条件表达式集合</param>
/// <param name="orderExp">排序表达式</param>
/// <param name="orderType">排序类型</param>
/// <param name="pageIndex">页码(从0开始)</param>
/// <param name="pageSize">每页条数</param>
/// <returns></returns>
public static IPagedList<TSource> GetPageList<TSource>(this SqlSugarClient db, List<IConditionalModel> conditionals, Expression<Func<TSource, object>> orderExp, OrderByType orderType, int pageIndex, int pageSize) where TSource : EntityBase, new()
{
int count = ;
var result = db.Queryable<TSource>().Where(conditionals).OrderBy(orderExp, orderType).ToPageList(pageIndex, pageSize, ref count);
return new PagedList<TSource>(result, pageIndex, pageSize, count);
} /// <summary>
/// 获取分页列表【Sugar表达式条件,排序,页码,每页条数】
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="db"></param>
/// <param name="conditionals">Sugar条件表达式集合</param>
/// <param name="orderExp">排序表达式</param>
/// <param name="orderType">排序类型</param>
/// <param name="pageIndex">页码(从0开始)</param>
/// <param name="pageSize">每页条数</param>
/// <returns></returns>
public static IPagedList<TMap> GetPageList<TSource, TMap>(this SqlSugarClient db, List<IConditionalModel> conditionals, Expression<Func<TSource, object>> orderExp, OrderByType orderType, int pageIndex, int pageSize) where TSource : EntityBase, new()
{
int count = ;
var result = db.Queryable<TSource>().Where(conditionals).OrderBy(orderExp, orderType).ToPageList(pageIndex, pageSize, ref count);
var pageResult = new PagedList<TSource>(result, pageIndex, pageSize, count);
return pageResult.Map<TSource, TMap>();
} #endregion #region 分页查询 (扩展条件构造实体,默认排序列,默认排序方式)
/// <summary>
/// 分页查询 (扩展条件构造实体,默认排序列,默认排序方式)
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TMap"></typeparam>
/// <param name="db"></param>
/// <param name="query"></param>
/// <param name="defaultSort"></param>
/// <param name="defaultSortType"></param>
/// <returns></returns>
public static IPagedList<TMap> GetPageList<TSource, TMap>(this SqlSugarClient db, QueryCollection query, Expression<Func<TSource, object>> defaultSort, OrderByType defaultSortType) where TSource : EntityBase, new()
{
int count = ;
List<IConditionalModel> conditionals = query.ConditionItems.ExamineConditional<TSource>();
Expression<Func<TSource, object>> sort = query.SortLambda<TSource, object>(defaultSort, defaultSortType, out var sortType);
var result = db.Queryable<TSource>().Where(conditionals).OrderBy(sort, sortType).ToPageList(query.PageIndex, query.PageSize, ref count);
var pageResult = new PagedList<TSource>(result, query.PageIndex, query.PageSize, count);
return pageResult.Map<TSource, TMap>();
}
#endregion #region 分页查询 (扩展条件构造实体,默认排序列,默认排序方式,Linq表达式条件)
/// <summary>
/// 分页查询 (扩展条件构造实体,默认排序列,默认排序方式,Linq表达式条件)
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TMap"></typeparam>
/// <param name="db"></param>
/// <param name="query"></param>
/// <param name="defaultSort"></param>
/// <param name="defaultSortType"></param>
/// <param name="whereExp"></param>
/// <returns></returns>
public static IPagedList<TMap> GetPageList<TSource, TMap>(this SqlSugarClient db, QueryCollection query, Expression<Func<TSource, object>> defaultSort, OrderByType defaultSortType, Expression<Func<TSource, bool>> whereExp) where TSource : EntityBase, new()
{
int count = ;
List<IConditionalModel> conditionals = query.ConditionItems.ExamineConditional<TSource>();
Expression<Func<TSource, object>> sort = query.SortLambda<TSource, object>(defaultSort, defaultSortType, out var sortType);
var result = db.Queryable<TSource>().Where(whereExp).Where(conditionals).OrderBy(sort, sortType).ToPageList(query.PageIndex, query.PageSize, ref count);
var pageResult = new PagedList<TSource>(result, query.PageIndex, query.PageSize, count);
return pageResult.Map<TSource, TMap>();
}
#endregion
}

SugarFactoryExtensions,自行斟酌,喜欢使用sugar原生的,可跳过

使用:

             services.AddSqlSugarClient<DbFactory>((sp, op) =>
{
op.ConnectionString = sp.GetService<IConfiguration>().GetConnectionString("lucy");
op.DbType = DbType.MySql;
op.IsAutoCloseConnection = true;
op.InitKeyType = InitKeyType.Attribute;
op.IsShardSameThread = true;
});

注入

     //如果数据操作简单,直接在业务层使用
public class UsersService : Repository<DbFactory, IUsersRepository>, IUsersService
{
public UsersService(DbFactory factory, IUsersRepository) : base(factory)
{ } public async Task TestMethod()
{
//获取数据库上下文
//第一种
DbContext.Insert<Users>(new Users());
//第二种
using (var db = Factory.GetDbContext())
{
db.Insert<Users>(new Users());
db.Update<Users>(new Users());
}
//数据操作繁琐的放到自定义的IUsersRepository中
await DbRepository.TestAddAsync();
} }

业务层使用示例

  public class UsersRepository : Repository<DbFactory>, IUsersRepository
{
public UsersRepository(DbFactory factory) : base(factory)
{ } public async Task<bool> TestAddAsync()
{
//这里获取数据库上下文,与业务层一致 DbContext.Insert<Users>(new Users()); using (var db = Factory.GetDbContext())
{
db.Insert<Users>(new Users());
db.Update<Users>(new Users());
}
return await Task.FromResult(true);
}
}

仓储层(可省略,数据操作繁琐可以放这一层,简单的可以直接在业务层使用)

net core 使用 SqlSugar的更多相关文章

  1. 使用.Net Core Mvc +SqlSugar +Autofac+AutoMapper+....

    开源地址:https://github.com/AjuPrince/Aju.Carefree 目前用到了 SqlSugar.Dapper.Autofac.AutoMapper.Swagger.Redi ...

  2. .NET Core的SqlSugar上手使用小例子

    开始直接建个空的WEB项目-建Controllers文件夹-开启MVC-添加NuGet程序包SqlSugarCore public class Startup { // This method get ...

  3. .NET 开源SqlServer ORM框架 SqlSugar 3.0 API

    3.1.x ,将作为3.X系统的最后一个版本,下面将会开发 全新的功能 更新列表:https://github.com/sunkaixuan/SqlSugar/releases 优点: SqlSuga ...

  4. [开源ORM] SqliteSugar 3.x .net Core版本成功上线

    SqliteSqlSugar 3.X API 作为支持.NET CORE 为数不多的ORM之一,除了具有优越的性能外,还拥有强大的功能,不只是满足你的增,删,查和改.实质上拥有更多你想像不到的功能,当 ...

  5. N[开源].NET CORE与MySql更配, MySqlSugar ORM框架 3.x

    MySqlSugar 3.X API 作为支持.NET CORE 为数不多的ORM之一,除了具有优越的性能外,还拥有强大的功能,不只是满足你的增,删,查和改.实质上拥有更多你想像不到的功能,当你需要实 ...

  6. .Net开源SqlServer ORM框架SqlSugar整理

    一.链接整理 官方Git源代码地址: https://github.com/sunkaixuan/SqlSugar 最新发布版更新地址:当前版本Release 3.5.2.1 https://gith ...

  7. .Net Core ORM选择之路,哪个才适合你

    因为老板的一句话公司项目需要迁移到.Net Core ,但是以前同事用的ORM不支持.Net Core 开发过程也遇到了各种坑,插入条数多了也特别的慢,导致系统体验比较差好多都改写Sql实现. 所以我 ...

  8. .Net Core ORM选择之路,哪个才适合你 通用查询类封装之Mongodb篇 Snowflake(雪花算法)的JavaScript实现 【开发记录】如何在B/S项目中使用中国天气的实时天气功能 【开发记录】微信小游戏开发入门——俄罗斯方块

    .Net Core ORM选择之路,哪个才适合你   因为老板的一句话公司项目需要迁移到.Net Core ,但是以前同事用的ORM不支持.Net Core 开发过程也遇到了各种坑,插入条数多了也特别 ...

  9. 从零开始搭建WebAPI Core_SqlSugar管理系统 (持续更新中......)

    从零开始搭建WebAPI Core_SqlSugar管理系统 前言 本系列皆在从零开始逐步搭建,后台管理系统服务端部分,后续还会推出前端部分. 这次的目的是搭出一个功能完善的 本次系列技术栈以下几个部 ...

随机推荐

  1. Python函数-complex()

    complex([real[, imag]]) 作用: 创建一个值为real + imag * j的复数或者转化一个字符串或数为复数.如果第一个参数为字符串,则不需要指定第二个参数. 参数real: ...

  2. 难道调用ThreadPool.QueueUserWorkItem()的时候,真是必须调用Thread.Sleep(N)吗?

    开门见山,下面的例子中通过调用ThreadPool.QueueUserWorkItem(WaitCallback callBack, object state)的方式实现异步调用: 1: class ...

  3. jQuery 实现最简单的form表单提交 Loding 功能

    <html> <head><title></title></head> <body> <form name="e ...

  4. SPI驱动框架-1(DM8127 Linux2.6.37为例)

    一.驱动程序结构 1.platform_device 文件:/arch/arm/mach-omap2/device.c static struct omap2_mcspi_platform_confi ...

  5. python第十一天-----补:缓存操作

    memcached,首先下载python-memcached模块,在cmd中执行pip install python-memcached即可 memcached比较简单,默认情况仅支持简单的kv存储, ...

  6. JavaEE中的Cookie的基本使用方法

    之前一直使用的是统一登录系统,相关的登录由别的部门开发以及维护.但由于最近项目的需要,我们需要自己开发一套简单的登录功能.因此这里就涉及到了一个Cookie的功能.之前也了解过相关的内容,但这次需要独 ...

  7. Celery-4.1 用户指南:Testing with Celery (用 Celery测试)

    任务与单元测试 在单元测试中测试任务行为的推荐方法是用mocking. Eager mode: task_always_eager 设置启用的 eager 模式不适用于单元测试. 当使用eager模式 ...

  8. Python中str.format()字典及list传入详解

  9. 什么是SPU、SKU、SKC、ARPU

    首先,搞清楚商品与单品的区别.例如,iphone是一个单品,但是在淘宝上当很多商家同时出售这个产品的时候,iphone就是一个商品了. 商品:淘宝叫item,京东叫product,商品特指与商家有关的 ...

  10. Http服务端

    第一,使用node提供的http模块 var http=require('http'); 第二,创建一个服务器实例 通过http的createServer()方法. var server=http.c ...