using SqlSugar; using System.Collections.Generic; using System.Linq; namespace @Model.name_space { /***这里面写的代码不会给覆盖,如果要重新生成请删除 Repository.cs ***/ /// /// 仓储模式 /// /// public class Repository : SimpleClient where T : class, new() { /// /// 构造函数 /// /// public Repository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null { if (context == null) { base.Context = Db; } } /// /// SqlSugarScope操作数据库是线程安的可以单例 /// public static SqlSugarScope Db = new SqlSugarScope(new ConnectionConfig() { DbType = [请设置DbType], ConnectionString = [请设置ConStr], IsAutoCloseConnection = true }, db => { //如果用单例配置要统一写在这儿 db.Aop.OnLogExecuting = (s, p) => { }; }); /// /// 仓储扩展方法:单表查询通用分页 /// /// public object CommonPage(QueryParameters pars, int pageIndex, int pagesize) { int tolCount = 0; var sugarParamters = pars.Parameters.Select(it => (IConditionalModel)new ConditionalModel() { ConditionalType = it.ConditionalType, FieldName = it.FieldName, FieldValue = it.FieldValue }).ToList(); var query = Db.Queryable(); if (pars.OrderBys != null) { foreach (var item in pars.OrderBys) { query.OrderBy(item.ToSqlFilter());//格式 id asc或者 id desc } } var result = query.Where(sugarParamters).ToPageList(1, 2, ref tolCount); return new { count = tolCount, data = result }; } /// /// 仓储扩展方法:多表查询通用分页 /// 用法 CommonPage(db.Queryable(...).Select(it=new class(){..}).MergeTable(),pars,orderbys,pageIndex,pagesize) /// /// public object CommonPage(ISugarQueryable query, QueryParameters pars, int pageIndex, int pagesize) { int tolCount = 0; var sugarParamters = pars.Parameters.Select(it => (IConditionalModel)new ConditionalModel() { ConditionalType = it.ConditionalType, FieldName = it.FieldName, FieldValue = it.FieldValue }).ToList(); if (pars.OrderBys != null) { foreach (var item in pars.OrderBys) { query.OrderBy(item.ToSqlFilter());//格式 id asc或者 id desc } } var result = query.Where(sugarParamters).ToPageList(1, 2, ref tolCount); return new { count = tolCount, data = result }; } } /// /// 通用查询参数 /// public class QueryParameters { public List Parameters { get; set; } public List OrderBys { get; set; } } /// /// 通用查询参数 /// public class QueryParameter { public string FieldName { get; set; } public string FieldValue { get; set; } public ConditionalType ConditionalType { get; set; } } }