Beispiel #1
0
        /// <summary>
        /// 根据主键获取Entity
        /// </summary>
        /// <param name="Id">主键Id</param>
        /// <returns>Entity</returns>
        protected virtual TModel GetById(object Id)
        {
            TModel rv = null;
            //建立基础查询
            var query = DC.Set <TModel>().AsQueryable();

            //循环添加其他设定的Include
            if (_toInclude != null)
            {
                foreach (var item in _toInclude)
                {
                    query = query.Include(item);
                }
            }
            if (typeof(TModel).IsSubclassOf(typeof(PersistPoco)))
            {
                var mod    = new IsValidModifier();
                var newExp = mod.Modify(query.Expression);
                query = query.Provider.CreateQuery <TModel>(newExp) as IOrderedQueryable <TModel>;
            }

            //获取数据
            rv = query.CheckID(Id).AsNoTracking().SingleOrDefault();
            if (rv == null)
            {
                throw new Exception("数据不存在");
            }
            //如果TopBasePoco有关联的附件,则自动Include 附件名称
            var fa = typeof(TModel).GetProperties().Where(x => x.PropertyType == typeof(FileAttachment)).ToList();

            foreach (var f in fa)
            {
                var fname = DC.GetFKName2 <TModel>(f.Name);
                var fid   = typeof(TModel).GetProperty(fname).GetValue(rv) as Guid?;
                var file  = DC.Set <FileAttachment>().Where(x => x.ID == fid).Select(x => new FileAttachment {
                    ID           = x.ID,
                    CreateBy     = x.CreateBy,
                    CreateTime   = x.CreateTime,
                    UpdateBy     = x.UpdateBy,
                    UpdateTime   = x.UpdateTime,
                    UploadTime   = x.UploadTime,
                    FileExt      = x.FileExt,
                    FileName     = x.FileName,
                    Length       = x.Length,
                    GroupName    = x.GroupName,
                    IsTemprory   = x.IsTemprory,
                    Path         = x.Path,
                    SaveFileMode = x.SaveFileMode
                }).FirstOrDefault();
                rv.SetPropertyValue(f.Name, file);
            }

            return(rv);
        }
Beispiel #2
0
        /// <summary>
        /// 根据主键获取Entity
        /// </summary>
        /// <param name="Id">主键Id</param>
        /// <returns>Entity</returns>
        protected virtual TModel GetById(Guid Id)
        {
            TModel rv = null;
            //建立基础查询
            var query = DC.Set <TModel>().AsQueryable();

            //循环添加其他设定的Include
            if (_toInclude != null)
            {
                foreach (var item in _toInclude)
                {
                    query = query.Include(item);
                }
            }
            //获取数据
            rv = query.Where(x => x.ID == Id).SingleOrDefault();
            if (rv == null)
            {
                throw new Exception("数据不存在");
            }
            //如果TopBasePoco有关联的附件,则自动Include 附件名称
            var fa = typeof(TModel).GetProperties().Where(x => x.PropertyType == typeof(FileAttachment)).ToList();

            foreach (var f in fa)
            {
                var fname = DC.GetFKName2 <TModel>(f.Name);
                var fid   = typeof(TModel).GetProperty(fname).GetValue(rv) as Guid?;
                var file  = DC.Set <FileAttachment>().Where(x => x.ID == fid).Select(x => new FileAttachment {
                    ID           = x.ID,
                    CreateBy     = x.CreateBy,
                    CreateTime   = x.CreateTime,
                    UpdateBy     = x.UpdateBy,
                    UpdateTime   = x.UpdateTime,
                    UploadTime   = x.UploadTime,
                    FileExt      = x.FileExt,
                    FileName     = x.FileName,
                    Length       = x.Length,
                    GroupName    = x.GroupName,
                    IsTemprory   = x.IsTemprory,
                    Path         = x.Path,
                    SaveFileMode = x.SaveFileMode
                }).FirstOrDefault();
                rv.SetPropertyValue(f.Name, file);
            }

            return(rv);
        }
Beispiel #3
0
        /// <summary>
        /// 根据主键获取Entity
        /// </summary>
        /// <param name="Id">主键Id</param>
        /// <returns>Entity</returns>
        protected virtual TModel GetById(object Id)
        {
            TModel rv = null;
            //建立基础查询
            var query = DC.Set <TModel>().AsQueryable();

            //循环添加其他设定的Include
            if (_toInclude != null)
            {
                foreach (var item in _toInclude)
                {
                    query = query.Include(item);
                }
            }
            if (typeof(TModel).IsSubclassOf(typeof(PersistPoco)))
            {
                var mod    = new IsValidModifier();
                var newExp = mod.Modify(query.Expression);
                query = query.Provider.CreateQuery <TModel>(newExp) as IOrderedQueryable <TModel>;
            }

            //获取数据
            rv = query.CheckID(Id).AsNoTracking().SingleOrDefault();
            if (rv == null)
            {
                return(rv);
                //throw new Exception("数据不存在");
            }
            //如果TopBasePoco有关联的附件,则自动Include 附件名称
            var fa = typeof(TModel).GetAllProperties().Where(x => x.PropertyType == typeof(FileAttachment)).ToList();

            foreach (var f in fa)
            {
                var fname = DC.GetFKName2 <TModel>(f.Name);
                var fid   = typeof(TModel).GetSingleProperty(fname).GetValue(rv);
                if (fid != null)
                {
                    var fp   = KnifeVirgo.HttpContext.RequestServices.GetRequiredService <VirgoFileProvider>();
                    var file = fp.GetFile(fid?.ToString(), false, DC);
                    rv.SetPropertyValue(f.Name, file);
                }
            }

            return(rv);
        }
Beispiel #4
0
        public override IOrderedQueryable <CodeGenListView> GetSearchQuery()
        {
            Type modeltype            = Type.GetType(ModelFullName);
            var  pros                 = modeltype.GetProperties();
            List <CodeGenListView> lv = new List <CodeGenListView>();
            int count                 = 0;

            Type[]        basetype    = new Type[] { typeof(BasePoco), typeof(TopBasePoco), typeof(PersistPoco) };
            List <string> ignoreField = new List <string>();

            foreach (var pro in pros)
            {
                if (basetype.Contains(pro.DeclaringType) == false)
                {
                    if (pro.CanWrite == false)
                    {
                        continue;
                    }
                    if (pro.Name.ToLower() == "id" && pro.PropertyType != typeof(string))
                    {
                        continue;
                    }
                    CodeGenListView view = new CodeGenListView()
                    {
                        FieldName  = pro.Name,
                        FieldDes   = pro.GetPropertyDisplayName(),
                        SubIdField = "",
                        Index      = count
                    };
                    var  notmapped = pro.GetCustomAttributes(typeof(NotMappedAttribute), false).FirstOrDefault();
                    Type checktype = pro.PropertyType;
                    if (pro.PropertyType.IsNullable())
                    {
                        checktype = pro.PropertyType.GetGenericArguments()[0];
                    }
                    if (ignoreField.Contains(checktype.Name))
                    {
                        continue;
                    }
                    bool show = false;
                    view.IsFormField   = true;
                    view.IsListField   = true;
                    view.IsImportField = true;
                    if (checktype.IsPrimitive || checktype == typeof(string) || checktype == typeof(DateTime) || checktype.IsEnum() || checktype == typeof(decimal))
                    {
                        show = true;
                    }
                    if (typeof(TopBasePoco).IsAssignableFrom(checktype))
                    {
                        var fk = DC.GetFKName2(modeltype, pro.Name);
                        if (fk != null)
                        {
                            ignoreField.Add(fk);
                        }
                        if (checktype == typeof(FileAttachment))
                        {
                            view.IsImportField = false;
                            view.FieldDes     += $"({Program._localizer["Attachment"]})";
                        }
                        else
                        {
                            view.FieldDes += $"({Program._localizer["OneToMany"]})";
                        }
                        view.LinkedType = checktype.AssemblyQualifiedName;
                        show            = true;
                    }
                    if (checktype.IsList())
                    {
                        checktype = pro.PropertyType.GetGenericArguments()[0];
                        if (checktype.IsNullable())
                        {
                            checktype = checktype.GetGenericArguments()[0];
                        }
                        var middletable = checktype.GetCustomAttributes(typeof(MiddleTableAttribute), false).FirstOrDefault();
                        if (middletable != null)
                        {
                            view.FieldDes     += $"({Program._localizer["ManyToMany"]})";
                            view.IsImportField = false;
                            var subpros = checktype.GetProperties();
                            foreach (var spro in subpros)
                            {
                                if (basetype.Contains(spro.DeclaringType) == false)
                                {
                                    Type subchecktype = spro.PropertyType;
                                    if (spro.PropertyType.IsNullable())
                                    {
                                        subchecktype = spro.PropertyType.GetGenericArguments()[0];
                                    }
                                    if (typeof(TopBasePoco).IsAssignableFrom(subchecktype) && subchecktype != modeltype)
                                    {
                                        view.LinkedType = subchecktype.AssemblyQualifiedName;
                                        var fk = DC.GetFKName2(checktype, spro.Name);
                                        view.SubIdField = fk;
                                        show            = true;
                                    }
                                }
                            }
                        }
                    }
                    if (notmapped != null)
                    {
                        view.FieldDes       += "(NotMapped)";
                        view.IsFormField     = false;
                        view.IsSearcherField = false;
                        view.IsBatchField    = false;
                        view.IsImportField   = false;
                        view.IsListField     = false;
                    }
                    if (show == true)
                    {
                        lv.Add(view);
                        count++;
                    }
                }
            }

            for (int i = 0; i < lv.Count(); i++)
            {
                if (ignoreField.Contains(lv[i].FieldName))
                {
                    for (int j = i; j < lv.Count(); j++)
                    {
                        lv[j].Index--;
                    }
                    lv.RemoveAt(i);
                    i--;
                }
            }

            return(lv.AsQueryable().OrderBy(x => x.FieldName));
        }
        /// <summary>
        /// 批量删除,默认对Ids中包含的主键的数据进行删除。子类如果有特殊判断应重载本函数
        /// </summary>
        /// <returns>true代表成功,false代表失败</returns>
        public virtual bool DoBatchDelete()
        {
            bool rv = true;
            //循环所有数据Id
            List <string> idsData   = Ids.ToList();
            var           modelType = typeof(TModel);
            var           pros      = modelType.GetAllProperties();
            //如果包含附件,则先删除附件
            List <Guid> fileids   = new List <Guid>();
            var         fa        = pros.Where(x => x.PropertyType == typeof(FileAttachment) || typeof(TopBasePoco).IsAssignableFrom(x.PropertyType)).ToList();
            var         isPersist = modelType.IsSubclassOf(typeof(PersistPoco));
            var         query     = DC.Set <TModel>().AsQueryable();
            var         fas       = pros.Where(x => typeof(IEnumerable <ISubFile>).IsAssignableFrom(x.PropertyType)).ToList();

            foreach (var f in fas)
            {
                query = query.Include(f.Name);
            }
            query = query.AsNoTracking().CheckIDs(idsData);
            var entityList = query.ToList();

            for (int i = 0; i < entityList.Count; i++)
            {
                string checkErro = null;
                //检查是否可以删除,如不能删除则直接跳过
                if (CheckIfCanDelete(idsData[i], out checkErro) == false)
                {
                    ErrorMessage.Add(idsData[i], checkErro);
                    rv = false;
                    break;
                }
                //进行删除
                try
                {
                    var Entity = entityList[i];
                    if (isPersist)
                    {
                        (Entity as PersistPoco).IsValid    = false;
                        (Entity as PersistPoco).UpdateTime = DateTime.Now;
                        (Entity as PersistPoco).UpdateBy   = LoginUserInfo.ITCode;
                        DC.UpdateProperty(Entity, "IsValid");
                        DC.UpdateProperty(Entity, "UpdateTime");
                        DC.UpdateProperty(Entity, "UpdateBy");
                    }
                    else
                    {
                        foreach (var f in fa)
                        {
                            if (f.PropertyType == typeof(FileAttachment))
                            {
                                string fidfield = DC.GetFKName2(modelType, f.Name);
                                var    fidpro   = pros.Where(x => x.Name == fidfield).FirstOrDefault();
                                var    idresult = fidpro.GetValue(Entity);
                                if (idresult != null)
                                {
                                    Guid fid = Guid.Empty;
                                    if (Guid.TryParse(idresult.ToString(), out fid) == true)
                                    {
                                        fileids.Add(fid);
                                    }
                                }
                            }
                            f.SetValue(Entity, null);
                        }

                        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);
                            }
                            else
                            {
                            }
                        }
                        if (typeof(TModel) != typeof(FileAttachment))
                        {
                            foreach (var pro in pros)
                            {
                                if (pro.PropertyType.GetTypeInfo().IsSubclassOf(typeof(TopBasePoco)))
                                {
                                    pro.SetValue(Entity, null);
                                }
                            }
                        }
                        DC.DeleteEntity(Entity);
                    }
                }
                catch (Exception e)
                {
                    SetExceptionMessage(e, idsData[i]);
                    rv = false;
                }
            }
            //进行数据库的删除操作
            if (rv == true)
            {
                try
                {
                    DC.SaveChanges();
                    var fp = KnifeVirgo.HttpContext.RequestServices.GetRequiredService <VirgoFileProvider>();
                    foreach (var item in fileids)
                    {
                        fp.DeleteFile(item.ToString(), DC.ReCreate());
                    }
                }
                catch (Exception e)
                {
                    SetExceptionMessage(e, null);
                    rv = false;
                }
            }
            //如果失败,添加错误信息
            if (rv == false)
            {
                if (ErrorMessage.Count > 0)
                {
                    foreach (var id in idsData)
                    {
                        if (!ErrorMessage.ContainsKey(id))
                        {
                            ErrorMessage.Add(id, Core.CoreProgram.Callerlocalizer?["Sys.Rollback"]);
                        }
                    }
                }
                ListVM?.DoSearch();
                if (ListVM != null)
                {
                    foreach (var item in ListVM?.GetEntityList())
                    {
                        item.BatchError = ErrorMessage.Where(x => x.Key == item.GetID().ToString()).Select(x => x.Value).FirstOrDefault();
                    }
                }
                MSD.AddModelError("", Core.CoreProgram.Callerlocalizer?["Sys.DataCannotDelete"]);
            }
            return(rv);
        }