/// <summary> /// 物理删除,对于普通的TopBasePoco和Delete操作相同,对于PersistPoco则进行真正的删除。子类如有自定义操作应重载本函数 /// </summary> public virtual void DoRealDelete() { try { List <Guid> fileids = new List <Guid>(); var pros = typeof(TModel).GetProperties(); //如果包含附件,则先删除附件 var fa = pros.Where(x => x.PropertyType == typeof(FileAttachment) || typeof(TopBasePoco).IsAssignableFrom(x.PropertyType)).ToList(); foreach (var f in fa) { if (f.GetValue(Entity) is FileAttachment file) { fileids.Add(file.ID); } f.SetValue(Entity, null); } DC.DeleteEntity(Entity); DC.SaveChanges(); foreach (var item in fileids) { FileAttachmentVM ofa = new FileAttachmentVM(); ofa.CopyContext(this); ofa.SetEntityById(item); ofa.DoDelete(); } } catch (Exception e) { MSD.AddModelError("", "数据使用中,无法删除"); } }
/// <summary> /// 物理删除,对于普通的TopBasePoco和Delete操作相同,对于PersistPoco则进行真正的删除。子类如有自定义操作应重载本函数 /// </summary> public virtual void DoRealDelete() { try { DC.DeleteEntity(Entity); DC.SaveChanges(); var pros = typeof(TModel).GetProperties(); //如果包含附件,则先删除附件 var fa = pros.Where(x => x.PropertyType == typeof(FileAttachment)).ToList(); foreach (var f in fa) { if (f.GetValue(Entity) is FileAttachment file) { FileAttachmentVM ofa = new FileAttachmentVM(); ofa.CopyContext(this); ofa.SetEntityById(file.ID); ofa.DoDelete(); } } } catch (Exception e) { MSD.AddModelError("", "数据使用中,无法删除"); } }
/// <summary> /// 通过FileAttachmentVM获取其文件流 /// </summary> /// <param name="vm"></param> /// <param name="con"></param> /// <returns></returns> public static byte[] GetFileByteForDownLoadByVM(FileAttachmentVM vm, Configs con) { byte[] data = null; SaveFileModeEnum saveMode = vm.Entity.SaveFileMode == null ? con.FileUploadOptions.SaveFileMode : vm.Entity.SaveFileMode.Value; data = GetBytes(saveMode, vm.Entity, vm.DC); return(data); }
/// <summary> /// 物理删除,对于普通的TopBasePoco和Delete操作相同,对于PersistPoco则进行真正的删除。子类如有自定义操作应重载本函数 /// </summary> public virtual void DoRealDelete() { try { List <Guid> fileids = new List <Guid>(); var pros = typeof(TModel).GetProperties(); //如果包含附件,则先删除附件 var fa = pros.Where(x => x.PropertyType == typeof(FileAttachment) || typeof(TopBasePoco).IsAssignableFrom(x.PropertyType)).ToList(); foreach (var f in fa) { if (f.GetValue(Entity) is FileAttachment file) { fileids.Add(file.ID); } f.SetValue(Entity, null); } var fas = pros.Where(x => typeof(IEnumerable <ISubFile>).IsAssignableFrom(x.PropertyType)).ToList(); foreach (var f in fas) { var subs = f.GetValue(Entity) as IEnumerable <ISubFile>; if (subs != null) { foreach (var sub in subs) { fileids.Add(sub.FileId); } f.SetValue(Entity, null); } } if (typeof(TModel) != typeof(FileAttachment)) { foreach (var pro in pros) { if (pro.PropertyType.GetTypeInfo().IsSubclassOf(typeof(TopBasePoco))) { pro.SetValue(Entity, null); } } } DC.DeleteEntity(Entity); DC.SaveChanges(); foreach (var item in fileids) { FileAttachmentVM ofa = new FileAttachmentVM(); ofa.CopyContext(this); ofa.SetEntityById(item); ofa.DoDelete(); } } catch (Exception) { MSD.AddModelError("", Program._localizer["DeleteFailed"]); } }
/// <summary> /// 物理删除,对于普通的TopBasePoco和Delete操作相同,对于PersistPoco则进行真正的删除。子类如有自定义操作应重载本函数 /// </summary> public virtual void DoRealDelete() { try { List <Guid> fileids = new List <Guid>(); var pros = typeof(TModel).GetProperties(); //如果包含附件,则先删除附件 var fa = pros.Where(x => x.PropertyType == typeof(FileAttachment) || typeof(TopBasePoco).IsAssignableFrom(x.PropertyType)).ToList(); foreach (var f in fa) { if (f.GetValue(Entity) is FileAttachment file) { fileids.Add(file.ID); } f.SetValue(Entity, null); } var fas = pros.Where(x => typeof(IEnumerable <ISubFile>).IsAssignableFrom(x.PropertyType)).ToList(); foreach (var f in fas) { var subs = f.GetValue(Entity) as IEnumerable <ISubFile>; foreach (var sub in subs) { fileids.Add(sub.FileId); } f.SetValue(Entity, null); } using (var newdc = DC.ReCreate()) { TModel m = new TModel(); m.SetPropertyValue("ID", Entity.GetID()); newdc.Set <TModel>().Attach(m); newdc.DeleteEntity(m); newdc.SaveChanges(); } foreach (var item in fileids) { FileAttachmentVM ofa = new FileAttachmentVM(); ofa.CopyContext(this); ofa.SetEntityById(item); ofa.DoDelete(); } } catch (Exception e) { MSD.AddModelError("", "数据使用中,无法删除"); } }
public virtual async Task DoAddAsync() { DoAddPrepare(); //删除不需要的附件 if (DeletedFileIds != null) { foreach (var item in DeletedFileIds) { FileAttachmentVM ofa = new FileAttachmentVM(); ofa.CopyContext(this); ofa.SetEntityById(item); await ofa.DoDeleteAsync(); } } await DC.SaveChangesAsync(); }
/// <summary> /// 添加,进行默认的添加操作。子类如有自定义操作应重载本函数 /// </summary> public virtual void DoAdd() { DoAddPrepare(); //删除不需要的附件 if (DeletedFileIds != null) { foreach (var item in DeletedFileIds) { FileAttachmentVM ofa = new FileAttachmentVM(); ofa.CopyContext(this); ofa.SetEntityById(item); ofa.DoDelete(); } } DC.SaveChanges(); }
/// <summary> /// 修改,进行默认的修改操作。子类如有自定义操作应重载本函数 /// </summary> /// <param name="updateAllFields">为true时,框架会更新当前Entity的全部值,为false时,框架会检查Request.Form里的key,只更新表单提交的字段</param> public virtual void DoEdit(bool updateAllFields = false) { DoEditPrepare(updateAllFields); DC.SaveChanges(); //删除不需要的附件 if (DeletedFileIds != null) { foreach (var item in DeletedFileIds) { FileAttachmentVM ofa = new FileAttachmentVM(); ofa.CopyContext(this); ofa.SetEntityById(item); ofa.DoDelete(); } } }
/// <summary> /// 上传文件并返回FileAttachmentVM(后台代码使用) /// </summary> /// <param name="vm"></param> /// <param name="FileData"></param> /// <param name="con"></param> /// <param name="FileName"></param> /// <param name="savePlace"></param> /// <returns></returns> public static FileAttachmentVM GetFileByteForUpload(FileAttachmentVM vm, Stream FileData, Configs con, string FileName = null, SaveFileModeEnum?savePlace = null) { savePlace = savePlace == null ? con.SaveFileMode : savePlace; var ext = string.Empty; if (string.IsNullOrEmpty(FileName) == false) { var dotPos = FileName.LastIndexOf('.'); ext = FileName.Substring(dotPos + 1); } vm.Entity.FileName = FileName; vm.Entity.FileExt = ext; if (savePlace == SaveFileModeEnum.Database) { using (var dataStream = new System.IO.MemoryStream()) { FileData.CopyTo(dataStream); vm.Entity.FileData = new FileAttachmentData(); vm.Entity.FileData.FileData = dataStream.ToArray(); } } else if (savePlace == SaveFileModeEnum.Local) { string pathHeader = con.UploadDir; if (!Directory.Exists(pathHeader)) { Directory.CreateDirectory(pathHeader); } var fullPath = $"{pathHeader}/{Guid.NewGuid().ToNoSplitString()}.{vm.Entity.FileExt}"; using (var fileStream = File.Create(fullPath)) { FileData.CopyTo(fileStream); vm.Entity.Path = fullPath; vm.Entity.FileData = new FileAttachmentData(); } } FileData.Dispose(); return(vm); }
public ErrorObj GetErrorJson() { var mse = new ErrorObj(); mse.Form = new Dictionary <string, string>(); var err = ErrorListVM?.EntityList?.Where(x => x.Index == 0).FirstOrDefault()?.Message; if (string.IsNullOrEmpty(err)) { var fa = DC.Set <FileAttachment>().Where(x => x.ID == UploadFileId).SingleOrDefault(); hssfworkbook = FileHelper.GetHSSWorkbook(hssfworkbook, (FileAttachment)fa, ConfigInfo); var propetys = Template.GetType().GetFields().Where(x => x.FieldType == typeof(ExcelPropety)).ToList(); List <ExcelPropety> excelPropetys = new List <ExcelPropety>(); for (int porpetyIndex = 0; porpetyIndex < propetys.Count(); porpetyIndex++) { ExcelPropety ep = (ExcelPropety)propetys[porpetyIndex].GetValue(Template); excelPropetys.Add(ep); } int columnCount = excelPropetys.Count; //int excelPropetyCount = excelPropetys.Count; var dynamicColumn = excelPropetys.Where(x => x.DataType == ColumnDataType.Dynamic).FirstOrDefault(); if (dynamicColumn != null) { columnCount = columnCount + dynamicColumn.DynamicColumns.Count - 1; } ISheet sheet = hssfworkbook.GetSheetAt(0); var errorStyle = hssfworkbook.CreateCellStyle(); IFont f = hssfworkbook.CreateFont(); f.Color = HSSFColor.Red.Index; errorStyle.SetFont(f); errorStyle.IsLocked = true; foreach (var e in ErrorListVM?.EntityList) { if (e.Index > 0) { var c = sheet.GetRow((int)(e.Index - 1)).CreateCell(columnCount); c.CellStyle = errorStyle; c.SetCellValue(e.Message); } } MemoryStream ms = new MemoryStream(); hssfworkbook.Write(ms); ms.Position = 0; FileAttachmentVM vm = new FileAttachmentVM(); vm.CopyContext(this); vm.Entity.FileName = "Error-" + fa.FileName; vm.Entity.Length = ms.Length; vm.Entity.UploadTime = DateTime.Now; vm.Entity.SaveFileMode = ConfigInfo.FileUploadOptions.SaveFileMode; vm = FileHelper.GetFileByteForUpload(vm, ms, ConfigInfo, vm.Entity.FileName, null, null); vm.Entity.IsTemprory = true; if ((!string.IsNullOrEmpty(vm.Entity.Path) && (vm.Entity.SaveFileMode == SaveFileModeEnum.Local || vm.Entity.SaveFileMode == SaveFileModeEnum.DFS)) || (vm.Entity.FileData != null && vm.Entity.SaveFileMode == SaveFileModeEnum.Database)) { vm.DoAdd(); } ms.Close(); ms.Dispose(); err = "导入时发生错误"; mse.Form.Add("Entity.Import", err); mse.Form.Add("Entity.ErrorFileId", vm.Entity.ID.ToString()); } else { mse.Form.Add("Entity.Import", err); } return(mse); }
/// <summary> /// 修改,进行默认的修改操作。子类如有自定义操作应重载本函数 /// </summary> /// <param name="updateAllFields">为true时,框架会更新当前Entity的全部值,为false时,框架会检查Request.Form里的key,只更新表单提交的字段</param> public virtual void DoEdit(bool updateAllFields = false) { //自动设定修改日期和修改人 if (typeof(TModel).GetTypeInfo().IsSubclassOf(typeof(BasePoco))) { BasePoco ent = Entity as BasePoco; if (ent.UpdateTime == null) { ent.UpdateTime = DateTime.Now; } if (string.IsNullOrEmpty(ent.UpdateBy)) { ent.UpdateBy = LoginUserInfo?.ITCode; } } var pros = typeof(TModel).GetProperties(); #region 更新子表 foreach (var pro in pros) { //找到类型为List<xxx>的字段 if (pro.PropertyType.GenericTypeArguments.Count() > 0) { //获取xxx的类型 var ftype = pro.PropertyType.GenericTypeArguments.First(); //如果xxx继承自TopBasePoco if (ftype.IsSubclassOf(typeof(TopBasePoco))) { //界面传过来的子表数据 if (pro.GetValue(Entity) is IEnumerable <TopBasePoco> list && list.Count() > 0) { //获取外键字段名称 string fkname = DC.GetFKName <TModel>(pro.Name); PropertyInfo[] itemPros = ftype.GetProperties(); bool found = false; foreach (var newitem in list) { var subtype = newitem.GetType(); if (subtype.IsSubclassOf(typeof(BasePoco))) { BasePoco ent = newitem as BasePoco; if (ent.UpdateTime == null) { ent.UpdateTime = DateTime.Now; } if (string.IsNullOrEmpty(ent.UpdateBy)) { ent.UpdateBy = LoginUserInfo?.ITCode; } } //循环页面传过来的子表数据,将关联到TopBasePoco的字段设为null,并且把外键字段的值设定为主表ID foreach (var itempro in itemPros) { if (itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco))) { itempro.SetValue(newitem, null); } if (!string.IsNullOrEmpty(fkname)) { if (itempro.Name.ToLower() == fkname.ToLower()) { itempro.SetValue(newitem, Entity.ID); found = true; } } } } //如果没有找到相应的外建字段,则可能是多对多的关系,或者做了特殊的设定,这种情况框架无法支持,直接退出本次循环 if (found == false) { continue; } TModel _entity = null; //打开新的数据库联接,获取数据库中的主表和子表数据 using (var ndc = DC.CreateNew()) { _entity = ndc.Set <TModel>().Include(pro.Name).AsNoTracking().Where(x => x.ID == Entity.ID).FirstOrDefault(); } //比较子表原数据和新数据的区别 IEnumerable <TopBasePoco> toadd = null; IEnumerable <TopBasePoco> toremove = null; IEnumerable <TopBasePoco> data = _entity.GetType().GetProperty(pro.Name).GetValue(_entity) as IEnumerable <TopBasePoco>; Utils.CheckDifference(data, list, out toremove, out toadd); //设定子表应该更新的字段 List <string> setnames = new List <string>(); foreach (var field in FC.Keys) { if (field.StartsWith("Entity." + pro.Name + "[0].")) { string name = field.Replace("Entity." + pro.Name + "[0].", ""); setnames.Add(name); } } //前台传过来的数据 foreach (var newitem in list) { //数据库中的数据 foreach (var item in data) { //需要更新的数据 if (newitem.ID == item.ID) { dynamic i = newitem; var newitemType = item.GetType(); foreach (var itempro in itemPros) { if (!itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco)) && (updateAllFields == true || setnames.Contains(itempro.Name))) { var notmapped = itempro.GetCustomAttribute <NotMappedAttribute>(); if (itempro.Name != "ID" && notmapped == null && itempro.PropertyType.IsList() == false) { DC.UpdateProperty(i, itempro.Name); } } } DC.UpdateProperty(i, "UpdateTime"); DC.UpdateProperty(i, "UpdateBy"); } } } //需要删除的数据 foreach (var item in toremove) { foreach (var itempro in itemPros) { if (itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco))) { itempro.SetValue(item, null); } } dynamic i = item; DC.DeleteEntity(i); } //需要添加的数据 foreach (var item in toadd) { if (item.GetType().IsSubclassOf(typeof(BasePoco))) { BasePoco ent = item as BasePoco; if (ent.CreateTime == null) { ent.CreateTime = DateTime.Now; } if (string.IsNullOrEmpty(ent.CreateBy)) { ent.CreateBy = LoginUserInfo?.ITCode; } } DC.AddEntity(item); } } else if (FC.Keys.Contains("Entity." + pro.Name + ".DONOTUSECLEAR") || (pro.GetValue(Entity) is IEnumerable <TopBasePoco> list2 && list2?.Count() == 0)) { PropertyInfo[] itemPros = ftype.GetProperties(); var _entity = DC.Set <TModel>().Include(pro.Name).AsNoTracking().Where(x => x.ID == Entity.ID).FirstOrDefault(); if (_entity != null) { IEnumerable <TopBasePoco> removeData = _entity.GetType().GetProperty(pro.Name).GetValue(_entity) as IEnumerable <TopBasePoco>; foreach (var item in removeData) { foreach (var itempro in itemPros) { if (itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco))) { itempro.SetValue(item, null); } } dynamic i = item; DC.DeleteEntity(i); } } } } } } #endregion if (updateAllFields == false) { foreach (var field in FC.Keys) { if (field.StartsWith("Entity.") && !field.Contains("[")) { string name = field.Replace("Entity.", ""); try { DC.UpdateProperty(Entity, name); } catch (Exception) { } } } if (typeof(TModel).GetTypeInfo().IsSubclassOf(typeof(BasePoco))) { try { DC.UpdateProperty(Entity, "UpdateTime"); DC.UpdateProperty(Entity, "UpdateBy"); } catch (Exception) { } } } else { DC.UpdateEntity(Entity); } DC.SaveChanges(); //删除不需要的附件 if (DeletedFileIds != null) { foreach (var item in DeletedFileIds) { FileAttachmentVM ofa = new FileAttachmentVM(); ofa.CopyContext(this); ofa.SetEntityById(item); ofa.DoDelete(); } } }
/// <summary> /// 添加,进行默认的添加操作。子类如有自定义操作应重载本函数 /// </summary> public virtual void DoAdd() { var pros = typeof(TModel).GetProperties(); //将所有TopBasePoco的属性赋空值,防止添加关联的重复内容 if (typeof(TModel) != typeof(FileAttachment)) { foreach (var pro in pros) { if (pro.PropertyType.GetTypeInfo().IsSubclassOf(typeof(TopBasePoco))) { pro.SetValue(Entity, null); } } } //自动设定添加日期和添加人 if (typeof(TModel).GetTypeInfo().IsSubclassOf(typeof(BasePoco))) { BasePoco ent = Entity as BasePoco; if (ent.CreateTime == null) { ent.CreateTime = DateTime.Now; } if (string.IsNullOrEmpty(ent.CreateBy)) { ent.CreateBy = LoginUserInfo?.ITCode; } } if (typeof(TModel).GetTypeInfo().IsSubclassOf(typeof(PersistPoco))) { (Entity as PersistPoco).IsValid = true; } #region 更新子表 foreach (var pro in pros) { //找到类型为List<xxx>的字段 if (pro.PropertyType.GenericTypeArguments.Count() > 0) { //获取xxx的类型 var ftype = pro.PropertyType.GenericTypeArguments.First(); //如果xxx继承自TopBasePoco if (ftype.IsSubclassOf(typeof(BasePoco))) { //界面传过来的子表数据 IEnumerable <TopBasePoco> list = pro.GetValue(Entity) as IEnumerable <BasePoco>; if (list != null && list.Count() > 0) { string fkname = DC.GetFKName <TModel>(pro.Name); PropertyInfo[] itemPros = ftype.GetProperties(); bool found = false; foreach (var newitem in list) { foreach (var itempro in itemPros) { if (itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco))) { itempro.SetValue(newitem, null); } if (!string.IsNullOrEmpty(fkname)) { if (itempro.Name.ToLower() == fkname.ToLower()) { itempro.SetValue(newitem, Entity.ID); found = true; } } } } //如果没有找到相应的外建字段,则可能是多对多的关系,或者做了特殊的设定,这种情况框架无法支持,直接退出本次循环 if (found == false) { continue; } //循环页面传过来的子表数据,自动设定添加日期和添加人 foreach (var newitem in list) { var subtype = newitem.GetType(); BasePoco ent = newitem as BasePoco; if (ent.CreateTime == null) { ent.CreateTime = DateTime.Now; } if (string.IsNullOrEmpty(ent.CreateBy)) { ent.CreateBy = LoginUserInfo?.ITCode; } } } } } } #endregion //添加数据 DC.Set <TModel>().Add(Entity); //删除不需要的附件 if (DeletedFileIds != null) { foreach (var item in DeletedFileIds) { FileAttachmentVM ofa = new FileAttachmentVM(); ofa.CopyContext(this); ofa.SetEntityById(item); ofa.DoDelete(); } } DC.SaveChanges(); }
/// <summary> /// 上传文件并返回FileAttachmentVM(后台代码使用) /// </summary> /// <param name="vm"></param> /// <param name="FileData"></param> /// <param name="con"></param> /// <param name="FileName"></param> /// <param name="savePlace"></param> /// <param name="groupName"></param> /// <returns></returns> public static FileAttachmentVM GetFileByteForUpload(FileAttachmentVM vm, Stream FileData, Configs con, string FileName = null, SaveFileModeEnum?savePlace = null, string groupName = null) { savePlace = savePlace == null ? con.FileUploadOptions.SaveFileMode : savePlace; var ext = string.Empty; if (string.IsNullOrEmpty(FileName) == false) { var dotPos = FileName.LastIndexOf('.'); ext = FileName.Substring(dotPos + 1); } vm.Entity.FileName = FileName; vm.Entity.FileExt = ext; if (savePlace == SaveFileModeEnum.Database) { using (var dataStream = new MemoryStream()) { FileData.CopyTo(dataStream); vm.Entity.FileData = dataStream.ToArray(); } } else if (savePlace == SaveFileModeEnum.Local) { string pathHeader = con.FileUploadOptions.UploadDir; if (!Directory.Exists(pathHeader)) { Directory.CreateDirectory(pathHeader); } var fullPath = Path.Combine(con.FileUploadOptions.UploadDir, $"{Guid.NewGuid().ToNoSplitString()}.{vm.Entity.FileExt}"); using (var fileStream = File.Create(fullPath)) { FileData.CopyTo(fileStream); vm.Entity.Path = fullPath; vm.Entity.FileData = null; } } else if (savePlace == SaveFileModeEnum.DFS) { using (var dataStream = new MemoryStream()) { StorageNode node = null; FileData.CopyTo(dataStream); if (!string.IsNullOrEmpty(groupName)) { node = FDFSClient.GetStorageNode(groupName); } else { node = FDFSClient.GetStorageNode(); } if (node != null) { vm.Entity.Path = "/" + FDFSClient.UploadFile(node, dataStream.ToArray(), vm.Entity.FileExt); vm.Entity.GroupName = node.GroupName; } vm.Entity.FileData = null; } FileData.Dispose(); } return(vm); }