/// <summary> /// 创建重复数据信息 /// </summary> /// <param name="FieldExps">重复数据信息</param> /// <returns>重复数据信息</returns> protected DuplicatedInfo <TModel> CreateFieldsInfo(params DuplicatedField <TModel>[] FieldExps) { DuplicatedInfo <TModel> d = new DuplicatedInfo <TModel>(); d.AddGroup(FieldExps); return(d); }
/// <summary> /// 判断数据是否在库中存在重复数据 /// </summary> /// <param name="Entity">要验证的数据</param> /// <param name="checkCondition">验证表达式</param> /// <returns>null代表没有重复</returns> protected P IsDuplicateData(P Entity, DuplicatedInfo <P> checkCondition) { //获取设定的重复字段信息 if (checkCondition != null && checkCondition.Groups.Count > 0) { //生成基础Query var baseExp = DC.Set <P>().AsQueryable(); var modelType = typeof(P); ParameterExpression para = Expression.Parameter(modelType, "tm"); //循环所有重复字段组 foreach (var group in checkCondition.Groups) { List <Expression> conditions = new List <Expression>(); //生成一个表达式,类似于 x=>x.Id != id,这是为了当修改数据时验证重复性的时候,排除当前正在修改的数据 //在每个组中循环所有字段 List <PropertyInfo> props = new List <PropertyInfo>(); //在每个组中循环所有字段 foreach (var field in group.Fields) { Expression exp = field.GetExpression(Entity, para); if (exp != null) { conditions.Add(exp); } //将字段名保存,为后面生成错误信息作准备 props.AddRange(field.GetProperties()); } if (conditions.Count > 0) { //循环添加条件并生成Where语句 Expression conExp = conditions[0]; for (int i = 1; i < conditions.Count; i++) { conExp = Expression.And(conExp, conditions[i]); } MethodCallExpression whereCallExpression = Expression.Call( typeof(Queryable), "Where", new Type[] { modelType }, baseExp.Expression, Expression.Lambda <Func <P, bool> >(conExp, new ParameterExpression[] { para })); //Expression subSelect = Expression.Call( // typeof(Queryable), // "Select", // new Type[] { modelType, typeof(long)}, // whereCallExpression, // Expression.Lambda<Func<P, long>>(Expression.PropertyOrField(para, "Id"), new ParameterExpression[] { para })); var result = baseExp.Provider.CreateQuery(whereCallExpression); foreach (var res in result) { return(res as P); } } } } return(null); }
protected bool IsUpdateRecordDuplicated(DuplicatedInfo <P> checkCondition, P entity) { if (checkCondition != null && checkCondition.Groups.Count > 0) { //生成基础Query var baseExp = EntityList.AsQueryable(); var modelType = typeof(P); ParameterExpression para = Expression.Parameter(modelType, "tm"); //循环所有重复字段组 foreach (var group in checkCondition.Groups) { List <Expression> conditions = new List <Expression>(); //生成一个表达式,类似于 x=>x.Id != id,这是为了当修改数据时验证重复性的时候,排除当前正在修改的数据 MemberExpression idLeft = Expression.Property(para, "Id"); ConstantExpression idRight = Expression.Constant(entity.ID); BinaryExpression idNotEqual = Expression.NotEqual(idLeft, idRight); conditions.Add(idNotEqual); List <PropertyInfo> props = new List <PropertyInfo>(); //在每个组中循环所有字段 foreach (var field in group.Fields) { Expression exp = field.GetExpression(entity, para); if (exp != null) { conditions.Add(exp); } //将字段名保存,为后面生成错误信息作准备 props.AddRange(field.GetProperties()); } int count = 0; if (conditions.Count > 1) { //循环添加条件并生成Where语句 Expression conExp = conditions[0]; for (int i = 1; i < conditions.Count; i++) { conExp = Expression.And(conExp, conditions[i]); } MethodCallExpression whereCallExpression = Expression.Call( typeof(Queryable), "Where", new Type[] { modelType }, baseExp.Expression, Expression.Lambda <Func <P, bool> >(conExp, new ParameterExpression[] { para })); var result = baseExp.Provider.CreateQuery(whereCallExpression); foreach (var res in result) { count++; } } if (count > 0) { return(true); } } } return(false); }
/// <summary> /// 保存指定表中的数据 /// </summary> /// <returns>成功返回True,失败返回False</returns> public virtual bool BatchSaveData() { //如果没有赋值,则调用赋值函数 if (isEntityListSet == false) { SetEntityList(); } //如果在复制过程中已经有错误,则直接输出错误 if (ErrorListVM.EntityList.Count > 0) { DoReInit(); return(false); } //进行Model层面的验证 //找到对应的BaseCRUDVM,并初始化 var vms = this.GetType().Assembly.GetExportedTypes().Where(x => x.IsSubclassOf(typeof(BaseCRUDVM <P>))).ToList(); var vmtype = vms.Where(x => x.Name.ToLower() == typeof(P).Name.ToLower() + "vm").FirstOrDefault(); if (vmtype == null) { vmtype = vms.FirstOrDefault(); } IBaseCRUDVM <P> vm = null; DuplicatedInfo <P> dinfo = null; if (vmtype != null) { vm = vmtype.GetConstructor(System.Type.EmptyTypes).Invoke(null) as IBaseCRUDVM <P>; vm.CopyContext(this); dinfo = (vm as dynamic).SetDuplicatedCheck(); } var cinfo = this.SetDuplicatedCheck(); DuplicatedInfo <P> finalInfo = new DuplicatedInfo <P> { Groups = new List <DuplicatedGroup <P> >() }; if (dinfo == null) { dinfo = new DuplicatedInfo <P>(); } if (cinfo == null) { cinfo = new DuplicatedInfo <P>(); } if (dinfo.Groups != null) { foreach (var di in dinfo.Groups) { bool found = false; if (cinfo.Groups != null) { foreach (var ci in cinfo.Groups) { if (di.ToString() == ci.ToString()) { found = true; break; } } } if (found == false) { finalInfo.Groups.Add(di); } } } //调用controller方法验证model var vmethod = Controller?.GetType().GetMethod("RedoValidation"); foreach (var entity in EntityList) { try { vmethod.Invoke(Controller, new object[] { entity }); } catch { } if (vm != null) { vm.SetEntity(entity); vm.ByPassBaseValidation = true; vm.Validate(); var basevm = vm as BaseVM; if (basevm?.MSD?.Count > 0) { foreach (var key in basevm.MSD.Keys) { foreach (var error in basevm.MSD[key]) { ErrorListVM.EntityList.Add(new ErrorMessage { Message = error.ErrorMessage, Index = entity.ExcelIndex }); } } } } (vm as BaseVM)?.MSD.Clear(); //在本地EntityList中验证是否有重复 ValidateDuplicateData(finalInfo, entity); } //如果上述验证已经有错误,则直接输出错误 if (ErrorListVM.EntityList.Count > 0) { (vm as BaseVM)?.MSD.Clear(); DoReInit(); return(false); } //循环数据列表 foreach (var item in EntityList) { //根据唯一性的设定查找数据库中是否有同样的数据 P exist = IsDuplicateData(item, finalInfo); //如果有重复数据,则进行修改 if (exist != null) { //如果是普通字段,则直接赋值 var tempPros = typeof(T).GetFields(); foreach (var pro in tempPros) { var excelProp = Template.GetType().GetField(pro.Name).GetValue(Template) as ExcelPropety; var proToSet = typeof(P).GetProperties().Where(x => x.Name == excelProp.FieldName).FirstOrDefault(); if (proToSet != null) { var val = proToSet.GetValue(item); PropertyHelper.SetPropertyValue(exist, excelProp.FieldName, val, stringBasedValue: true); } } //更新修改时间字段 if (tempPros.Where(x => x.Name == "UpdateTime").SingleOrDefault() == null) { if (typeof(BasePoco).IsAssignableFrom(exist.GetType())) { (exist as BasePoco).UpdateTime = DateTime.Now; } } //更新修改人字段 if (tempPros.Where(x => x.Name == "UpdateBy").SingleOrDefault() == null) { if (typeof(BasePoco).IsAssignableFrom(exist.GetType())) { (exist as BasePoco).UpdateBy = LoginUserInfo.ITCode; } } exist.ExcelIndex = item.ExcelIndex; //更新字段 DC.UpdateEntity(exist); } //如果没有重复数据,则填加 else { if (typeof(BasePoco).IsAssignableFrom(item.GetType())) { (item as BasePoco).CreateTime = DateTime.Now; (item as BasePoco).CreateBy = LoginUserInfo?.ITCode; } if (typeof(PersistPoco).IsAssignableFrom(item.GetType())) { (item as PersistPoco).IsValid = true; } DC.Set <P>().Add(item); } } //如果有错误,则返回 if (ErrorListVM.EntityList.Count > 0) { DoReInit(); return(false); } //如果没有错误,更新数据库 if (EntityList.Count > 0) { try { DC.SaveChanges(); } catch (Exception e) { SetExceptionMessage(e, null); DoReInit(); return(false); } } return(true); }
protected void ValidateDuplicateData(DuplicatedInfo <P> checkCondition, P entity) { if (checkCondition != null && checkCondition.Groups.Count > 0) { //生成基础Query var baseExp = EntityList.AsQueryable(); var modelType = typeof(P); ParameterExpression para = Expression.Parameter(modelType, "tm"); //循环所有重复字段组 foreach (var group in checkCondition.Groups) { List <Expression> conditions = new List <Expression>(); //生成一个表达式,类似于 x=>x.Id != id,这是为了当修改数据时验证重复性的时候,排除当前正在修改的数据 var idproperty = modelType.GetProperties().Where(x => x.Name.ToLower() == "id").FirstOrDefault(); MemberExpression idLeft = Expression.Property(para, idproperty); ConstantExpression idRight = Expression.Constant(entity.GetID()); BinaryExpression idNotEqual = Expression.NotEqual(idLeft, idRight); conditions.Add(idNotEqual); List <PropertyInfo> props = new List <PropertyInfo>(); //在每个组中循环所有字段 foreach (var field in group.Fields) { Expression exp = field.GetExpression(entity, para); if (exp != null) { conditions.Add(exp); } //将字段名保存,为后面生成错误信息作准备 props.AddRange(field.GetProperties()); } int count = 0; if (conditions.Count > 1) { //循环添加条件并生成Where语句 Expression conExp = conditions[0]; for (int i = 1; i < conditions.Count; i++) { conExp = Expression.And(conExp, conditions[i]); } MethodCallExpression whereCallExpression = Expression.Call( typeof(Queryable), "Where", new Type[] { modelType }, baseExp.Expression, Expression.Lambda <Func <P, bool> >(conExp, new ParameterExpression[] { para })); var result = baseExp.Provider.CreateQuery(whereCallExpression); foreach (var res in result) { count++; } } if (count > 0) { //循环拼接所有字段名 string AllName = ""; foreach (var prop in props) { string name = PropertyHelper.GetPropertyDisplayName(prop); AllName += name + ","; } if (AllName.EndsWith(",")) { AllName = AllName.Remove(AllName.Length - 1); } //如果只有一个字段重复,则拼接形成 xxx字段重复 这种提示 if (props.Count == 1) { ErrorListVM.EntityList.Add(new ErrorMessage { Message = Program._localizer["DuplicateError", AllName], Index = entity.ExcelIndex }); } //如果多个字段重复,则拼接形成 xx,yy,zz组合字段重复 这种提示 else if (props.Count > 1) { ErrorListVM.EntityList.Add(new ErrorMessage { Message = Program._localizer["DuplicateGroupError", AllName], Index = entity.ExcelIndex }); } } } } }