net core 使用 SqlSugar
/// <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的更多相关文章
- 使用.Net Core Mvc +SqlSugar +Autofac+AutoMapper+....
开源地址:https://github.com/AjuPrince/Aju.Carefree 目前用到了 SqlSugar.Dapper.Autofac.AutoMapper.Swagger.Redi ...
- .NET Core的SqlSugar上手使用小例子
开始直接建个空的WEB项目-建Controllers文件夹-开启MVC-添加NuGet程序包SqlSugarCore public class Startup { // This method get ...
- .NET 开源SqlServer ORM框架 SqlSugar 3.0 API
3.1.x ,将作为3.X系统的最后一个版本,下面将会开发 全新的功能 更新列表:https://github.com/sunkaixuan/SqlSugar/releases 优点: SqlSuga ...
- [开源ORM] SqliteSugar 3.x .net Core版本成功上线
SqliteSqlSugar 3.X API 作为支持.NET CORE 为数不多的ORM之一,除了具有优越的性能外,还拥有强大的功能,不只是满足你的增,删,查和改.实质上拥有更多你想像不到的功能,当 ...
- N[开源].NET CORE与MySql更配, MySqlSugar ORM框架 3.x
MySqlSugar 3.X API 作为支持.NET CORE 为数不多的ORM之一,除了具有优越的性能外,还拥有强大的功能,不只是满足你的增,删,查和改.实质上拥有更多你想像不到的功能,当你需要实 ...
- .Net开源SqlServer ORM框架SqlSugar整理
一.链接整理 官方Git源代码地址: https://github.com/sunkaixuan/SqlSugar 最新发布版更新地址:当前版本Release 3.5.2.1 https://gith ...
- .Net Core ORM选择之路,哪个才适合你
因为老板的一句话公司项目需要迁移到.Net Core ,但是以前同事用的ORM不支持.Net Core 开发过程也遇到了各种坑,插入条数多了也特别的慢,导致系统体验比较差好多都改写Sql实现. 所以我 ...
- .Net Core ORM选择之路,哪个才适合你 通用查询类封装之Mongodb篇 Snowflake(雪花算法)的JavaScript实现 【开发记录】如何在B/S项目中使用中国天气的实时天气功能 【开发记录】微信小游戏开发入门——俄罗斯方块
.Net Core ORM选择之路,哪个才适合你 因为老板的一句话公司项目需要迁移到.Net Core ,但是以前同事用的ORM不支持.Net Core 开发过程也遇到了各种坑,插入条数多了也特别 ...
- 从零开始搭建WebAPI Core_SqlSugar管理系统 (持续更新中......)
从零开始搭建WebAPI Core_SqlSugar管理系统 前言 本系列皆在从零开始逐步搭建,后台管理系统服务端部分,后续还会推出前端部分. 这次的目的是搭出一个功能完善的 本次系列技术栈以下几个部 ...
随机推荐
- 系列文章--Silverlight与WCF通信
Silverlight与WCF通信(一) :Silverlight通过httpBinding访问IIS宿主WCF 摘要: 首语本人在学习Silverlight 和 WCF的时候,各种问题层出不穷,在园 ...
- python中print的几种用法
python中的print有几种常用的用法: 1. print("first example") 2. print("second", "exampl ...
- -3dB的理解
-3dB到底是什么?集成运放-3dB带宽又是什么? 以无源高通电路为例,介绍-3dB的意义. 输出与输入只比: Au=Uo/Ui=R/(R+1/j*2*PI*f*C)=1/(1+1/j*2*PI*f* ...
- 机器学习:SVM(SVM 思想解决回归问题)
一.SVM 思想在解决回归问题上的体现 回归问题的本质:找到一条直线或者曲线,最大程度的拟合数据点: 怎么定义拟合,是不同回归算法的关键差异: 线性回归定义拟合方式:让所有数据点到直线的 MSE 的值 ...
- Mysql 5.6 MHA (gtid) on Kylin
mha on Kylinip hostname repl role mha role192.168.19.69 mysql1 master node192.168.19.73 mysql2 slave ...
- 【转】onclick事件与href='javascript:function()'的区别
href='javascript:function()'和onclick能起到同样的效果,一般来说,如果要调用脚本还是在onclick事件里面写代码,而不推荐在href='javascript:fun ...
- 基于windows平台的命令行软件安装工具Chocolatey的安装
本文介绍Chocolatey的安装和使用 Chocolatey 这是基于.NET Framework 4以上的windows安装软件的命令行工具 安装 第一步,打开你的powershell.exe,使 ...
- javascript——对象的概念——函数 1 (函数对象的属性和方法)
一.创建函数 函数是一种对象:Function类 是对象,可以通过 Function 实例化一个函数,不过最多的还是利用 function 来创建函数. 方式一:利用 Function类 来实例化函数 ...
- DAY15-Django模板语言
Django模板系统 官方文档 你可能已经注意到我们在例子视图中返回文本的方式有点特别. 也就是说,HTML被直接硬编码在 Python代码之中. def current_datetime(reque ...
- 根据URL下载文件
commons-io 包中已经封装好了,直接可以使用 一.添加依赖 <dependency> <groupId>org.apache.commons</groupId&g ...