using JiepeiWMS.IRepository.Base; using JiepeiWMS.Model.Interfaces; using System.Linq; using System.Threading.Tasks; using JiepeiWMS.Extends; using System; namespace JiepeiWMS.Repository.Base { /// /// 排序扩展 /// public static class ExtSortBy { /// /// 移动到指定目标Id位置(可以批量移动,多条数据按ID由小到大排列)需配合事务,防止错误时可回滚 /// /// 模型类型 /// 仓储类 /// 指定目标Id /// 符合附加条件记录进行排序 /// 模型列表 /// 返回仓储类 public static async Task> _SortByMoveTo(this IBaseRepository Dal, int TargetId, string Where, params T[] Models) where T : class, IModSortBy { var tableName = typeof(T).Name; var fieldSortBy = "SortById"; var where = string.IsNullOrEmpty(Where) ? string.Empty : Where + " and "; var ids = string.Join(",", Models.Select(t => t.Id)); //先更新当前排序编号,再更新当前信息之后的 var tb = await Dal.QueryTable(string.Format("select {1} from {0} where Id={2};", tableName, fieldSortBy, TargetId)); int tsortid = tb.Rows.Count > 0 ? (int)tb.Rows[0][0] : 0; int sortid = tsortid; //是否放置最后 if (tsortid == 0) { var sqlmax = string.Format("select max({0}) from [{1}] where {2}", fieldSortBy, tableName, where.Substring(0,where.Length-5)); tb = await Dal.QueryTable(sqlmax); var objmax = tb.Rows.Count > 0 ? tb.Rows[0][0] : null; sortid = objmax == null || objmax == DBNull.Value ? 1 : (int)objmax; } foreach (var mod in Models) { mod.SortById = sortid + 1; } //移动到目标之前时需更新目标后面的数据 if (tsortid > 0) { var sql = string.Format(@" update [{0}] set {1}={1}+2 where {2}{1}>={4}; update [{0}] set {1}={1}-2 where {2}Id<{5} and {1}={4}+2; update [{0}] set {1}={4}+1 where Id in ({3}); ", tableName, fieldSortBy, where, ids, sortid, TargetId); var obj = Dal.ExecuteSqlCommand(sql); } return Dal; } /// /// 移动到指定目标Id位置(可以批量移动,多条数据按ID由小到大排列) /// /// 模型类型 /// 仓储类 /// 指定目标Id /// 符合附加条件记录进行排序 /// 模型列表 /// 返回仓储类 public static async Task> _SortByMoveTo(this IBaseRepository Dal, int TargetId, params T[] Modes) where T : class, IModSortBy { var obj = _SortByMoveTo(Dal, TargetId, string.Empty, Modes); return Dal; } } }