NHibernate查询示例合集

基本查询

 

复杂查询示例

/// <summary>
        /// 获取自定义表单数据中属于部门的部分
        /// </summary>
        /// <param name="month"></param>
        /// <param name="departmentId"></param>
        /// <param name="positionId"></param>
        /// <param name="fillUserName"></param>
        /// <param name="departmentName"></param>
        /// <param name="formName"></param>
        /// <param name="fieldName"></param>
        /// <param name="assesserName"></param>
        /// <returns></returns>
        public IList<CustomFormResultItem> GetDepartmentCustomFormItems(DateTime month, Guid? customFormId, Guid? departmentId, string fillUserName = "", string departmentName = "", string formName = "", string fieldName = "", string assesserName = "")
        {
            return GetCustomFormItemInternal(2, month, customFormId, departmentId, null, fillUserName, departmentName, formName, fieldName, assesserName);
        }

        public IList<CustomFormResultItem> GetCustomFormItemInternal(int? userorDeptControlType, DateTime month, Guid? customFormId, Guid? departmentId, Guid? positionId,
            string fillUserName = "", string belongToUserOrDepartmentName = "", string formName = "", string fieldName = "", string assesserName = "")
        {
            var query = _customFormResultItemRep.CreateCriteriaQuery()
               .CreateAlias("t.Result", "result")

               .CreateAlias("result.CreateUser", "createUser")
               .CreateAlias("t.FormItem", "formItem")
               .CreateAlias("result.CustomForm", "customForm");

            if (month == DateTime.MinValue)
                month = DateTime.Now;

            //Filter by month
            query.Add(Restrictions.Eq(Projections.SqlFunction(new SQLFunctionTemplate(NHibernateUtil.Int16, "datediff(month,?1,?2)"),
                NHibernateUtil.Int16, Projections.Property("CreateDate"), Projections.Constant(month)), 0));

            if (userorDeptControlType.HasValue)
            {
                if (userorDeptControlType == (int)FormControl.姓名)
                {
                    query.CreateAlias("result.BelongUser", "belongUser");
                    if (departmentId.HasValue && departmentId != Guid.Empty)
                    {
                        query.Add(Restrictions.Eq("belongUser.Department.Id", departmentId));
                    }
                    if (positionId.HasValue && positionId != Guid.Empty)
                    {
                        query.Add(Restrictions.Eq("belongUser.Position.Id", positionId));
                    }
                    if (!string.IsNullOrWhiteSpace(belongToUserOrDepartmentName))
                    {
                        query.Add(Restrictions.Like("belongUser.Name", belongToUserOrDepartmentName, MatchMode.Anywhere));
                    }
                }
                else if (userorDeptControlType == (int)FormControl.部门)
                {
                    query.CreateAlias("result.BelongDepartment", "belongDepartment");

                    if (departmentId.HasValue && departmentId != Guid.Empty)
                    {
                        query.Add(Restrictions.Eq("belongDepartment.Id", departmentId));
                    }
                    //if (positionId.HasValue && positionId != Guid.Empty)
                    //{
                    //    query.Add(Restrictions.Eq("belongUser.Position.Id", positionId));
                    //}
                    if (!string.IsNullOrWhiteSpace(belongToUserOrDepartmentName))
                    {
                        query.Add(Restrictions.Like("belongDepartment.Name", belongToUserOrDepartmentName, MatchMode.Anywhere));
                    }
                }

                var customFormSubQuery = DetachedCriteria.For<CustomFormItem>("cfi")
                    .CreateAlias("CustomForm", "cf")
                    .Add(Restrictions.Eq("cfi.FieldType", (FormControl)userorDeptControlType))
                     .SetResultTransformer(Transformers.DistinctRootEntity)
                    .SetProjection(Projections.Property("cf.Id"));

                query.Add(Subqueries.PropertyIn("customForm.Id", customFormSubQuery));

                if (userorDeptControlType == (int)FormControl.姓名)
                {
                    query.AddOrder(new Order("belongUser.Name", true));
                }
                else
                {
                    query.AddOrder(new Order("belongDepartment.Name", true));
                }
            }

            if (!string.IsNullOrWhiteSpace(fillUserName))
            {
                query.Add(Restrictions.Like("createUser.Name", fillUserName, MatchMode.Anywhere));
            }
            if (!string.IsNullOrWhiteSpace(formName))
            {
                query.Add(Restrictions.Like("customForm.Name", formName, MatchMode.Anywhere));
            }
            if (customFormId != null && customFormId != Guid.Empty)
            {
                query.Add(Restrictions.Eq("customForm.Id", customFormId));
            }

            if (!string.IsNullOrWhiteSpace(fieldName))
            {
                query.Add(Restrictions.Like("t.FieldName", fieldName, MatchMode.Anywhere));
            }
            if (!string.IsNullOrEmpty(assesserName))
            {
                query.Add(Restrictions.Like("createUser.Name", assesserName, MatchMode.Anywhere));
            }

            var types = new List<FormControl>() { FormControl.单选, FormControl.多选, FormControl.引用部门, FormControl.指标标准, FormControl.数字框, FormControl.文本框, FormControl.日期, FormControl.段落 }.ToArray();
            if (types.Length > 0)
                query.Add(Restrictions.In("formItem.FieldType", types));

            query.AddOrder(new Order("result.Id", true));
            query.AddOrder(new Order("formItem.OrderByIndex", true));

            query.SetMaxResults(100);

            var resultList = query.List<CustomFormResultItem>();
            return resultList;
        }

 

数据库函数查询示例

public IList<DepartmentIndicatorResult> SearchDepartmentIndicatorResult(DateTime evaluateMonth, Guid? departmentId, string indicatorName, string departmentName)
        {
            var query = this._departmentIndicatorResultRep.CreateCriteriaQuery().CreateAlias("t.Department", "dept").CreateAlias("t.Indicator", "indicator");

            if (evaluateMonth == DateTime.MinValue)
                evaluateMonth = DateTime.Now;
            //Filter by month
            query.Add(Restrictions.Eq(Projections.SqlFunction(new SQLFunctionTemplate(NHibernateUtil.Int16, "datediff(month,?1,?2)"), NHibernateUtil.Int16, Projections.Property("PointDate"), Projections.Constant(evaluateMonth)), 0));
            //filter by day
            //query.Add(Restrictions.Eq(Projections.SqlFunction(new SQLFunctionTemplate(NHibernateUtil.Int16, "datediff(day,?1,?2)"), NHibernateUtil.Int16, Projections.Property("PointDate"), Projections.Constant(evaluateMonth)), 0));

            if (departmentId.HasValue && departmentId != Guid.Empty)
            {
                query.Add(Restrictions.Eq("user.Department.Id", departmentId));
            }

            if (!string.IsNullOrWhiteSpace(departmentName))
            {
                query.Add(Restrictions.Like("dept.Name", departmentName, MatchMode.Anywhere));
            }
            if (!string.IsNullOrWhiteSpace(indicatorName))
            {
                query.Add(Restrictions.Like("indicator.Name", indicatorName, MatchMode.Anywhere));
            }
            //query.Add(Restrictions.Eq("indicator.DataCollectorType", DataCollectorType.月底收集));

            query.SetMaxResults(100);
            //query.AddOrder(new Order("pos.Name", true));

            var resultList = query.List<DepartmentIndicatorResult>();
            return resultList;
        }

查询示例展示

/// <summary>
        /// 查询员工指标考核结果(日评,月底指标考核成绩)
        /// </summary>
        /// <param name="dateRangeType"></param>
        /// <param name="date"></param>
        /// <param name="departmentId"></param>
        /// <param name="positionId"></param>
        /// <param name="indicatorName"></param>
        /// <param name="userName"></param>
        /// <param name="dataCollectorTypes"></param>
        /// <returns></returns>
        private IList<UserIndicatorResult> SearchUserIndicatorResult(DateRangeType dateRangeType, DateTime date, Guid? departmentId = null, Guid? positionId = null, string indicatorName = null,
            string userName = null, IList<DataCollectorType> dataCollectorTypes = null, IList<DataInputType> dataInputTypes = null, Guid? userId = null, Guid? indicatorId = null, int limit = 200, bool isAssess = true)
        {
            var query = this._userIndicatorResultRep.CreateCriteriaQuery().CreateAlias("t.User", "user").CreateAlias("t.Indicator", "indicator")
                .Add(Restrictions.Eq("t.DateRangeType", dateRangeType));

            if (date == DateTime.MinValue)
                date = DateTime.Now;
            if (dateRangeType == DateRangeType.Monthly || (dataCollectorTypes != null && dataCollectorTypes.Contains(DataCollectorType.月底收集)))
            {
                //Filter by month
                query.Add(Restrictions.Eq(Projections.SqlFunction(new SQLFunctionTemplate(NHibernateUtil.Int16, "datediff(month,?1,?2)"), NHibernateUtil.Int16, Projections.Property("PointDate"), Projections.Constant(date)), 0));
            }
            else if (dateRangeType == DateRangeType.Daily)
            {
                //filter by day
                query.Add(Restrictions.Eq(Projections.SqlFunction(new SQLFunctionTemplate(NHibernateUtil.Int16, "datediff(day,?1,?2)"), NHibernateUtil.Int16, Projections.Property("PointDate"), Projections.Constant(date)), 0));
            }

            if (departmentId.HasValue && departmentId != Guid.Empty)
            {
                query.Add(Restrictions.Eq("user.Department.Id", departmentId));
            }
            if (positionId.HasValue && positionId != Guid.Empty)
            {
                query.Add(Restrictions.Eq("user.Position.Id", positionId));
            }
            if (isAssess)
            {
                //todo
                query.Add(Restrictions.IsNotNull("TextResult"));
            }
            else
            {
                query.Add(Restrictions.IsNull("TextResult"));
            }
            if (!string.IsNullOrWhiteSpace(userName))
            {
                query.Add(Restrictions.Like("user.Name", userName, MatchMode.Anywhere));
            }
            if (userId.HasValue)
            {
                query.Add(Restrictions.Eq("user.Id", userId.Value));
            }
            if (indicatorId.HasValue)
            {
                query.Add(Restrictions.Eq("indicator.Id", indicatorId.Value));
            }
            if (!string.IsNullOrWhiteSpace(indicatorName))
            {
                query.Add(Restrictions.Like("indicator.Name", indicatorName, MatchMode.Anywhere));
            }

            if (dataCollectorTypes != null)
                query.Add(Restrictions.In("indicator.DataCollectorType", dataCollectorTypes.ToArray()));
            if (dataInputTypes != null)
                query.Add(Restrictions.In("indicator.DataInputType", dataInputTypes.ToArray()));

            //query.Add(Restrictions.Eq("indicator.DataCollectorType", DataCollectorType.月底收集));

            //为了性能的考虑,每次值允许拉200条记录
            query.SetMaxResults(limit);
            query.AddOrder(new Order("user.Name", true));

            var resultList = query.List<UserIndicatorResult>();
            return resultList;
        }

 

public IList<PositionIndicator> SearchPositionIndicatorList(
            List<Guid> departmentIds = null, Guid? departmentId = null, string departmentName = null,
            List<Guid> positionIds = null, Guid? positionId = null, string positionName = null,
            List<Guid> linkedFormIds = null, Guid? linkedFormId = null,
            string indicatorName = null,
            EvaluateType? evaluateType = null,
            string dataSource = null,
            string discriminant = null,
            Guid? crossAssesserId = null,
            string crossAssesserName = null,
            List<DataCollectorType> dataCollectorTypes = null, DataCollectorType? dataCollectorType = null,
            int limit = 200)
        {
            var query = CreateCriteriaQuery<PositionIndicator>()
                .CreateAlias("t.Position", "pos").CreateAlias("t.CrossAssesser", "ca", JoinType.LeftOuterJoin);

            #region Special Query
            if (departmentIds != null || departmentId.HasValue)
            {
                if (departmentIds == null)
                    departmentIds = new List<Guid>();
                if (departmentId.HasValue)
                    departmentIds.Add(departmentId.Value);

                var positionSubquery = DetachedCriteria.For<Department>()
                    .CreateAlias("Positions", "pos", NHibernate.SqlCommand.JoinType.InnerJoin)
                    .Add(Restrictions.In("Id", departmentIds.ToArray()))
                    .SetProjection(Projections.Property("pos.Id"));

                query.Add(Subqueries.PropertyIn("pos.Id", positionSubquery));
            }

            if (!string.IsNullOrWhiteSpace(departmentName))
            {
                var positionSubquery = DetachedCriteria.For<Department>()
                       .CreateAlias("Positions", "pos", NHibernate.SqlCommand.JoinType.InnerJoin)
                       .Add(Restrictions.Like("Name", departmentName, MatchMode.Anywhere))
                       .SetProjection(Projections.Property("pos.Id"));

                query.Add(Subqueries.PropertyIn("pos.Id", positionSubquery));
            }

            if (positionIds != null || positionId.HasValue)
            {
                if (positionIds == null)
                    positionIds = new List<Guid>();
                if (positionId.HasValue)
                    positionIds.Add(positionId.Value);
                if (positionIds.Count > 0)
                    query.Add(Restrictions.In("t.Position.Id", positionIds.ToArray()));
            }

            if (!string.IsNullOrWhiteSpace(positionName))
            {
                query.Add(Restrictions.Like("t.Position.Name", positionName, MatchMode.Anywhere));
            }
            #endregion

            BindIndicatorQuery(query, linkedFormIds, linkedFormId, indicatorName, evaluateType, dataSource, discriminant, crossAssesserId, crossAssesserName, dataCollectorTypes, dataCollectorType, limit);

            return query.List<PositionIndicator>();
        }

        public IList<DeptIndicator> SearchDepartmentIndicatorList(
            List<Guid> departmentIds = null, Guid? departmentId = null, string departmentName = null,
            List<Guid> linkedFormIds = null, Guid? linkedFormId = null,
            string indicatorName = null,
            EvaluateType? evaluateType = null,
            string dataSource = null,
            string discriminant = null,
            Guid? crossAssesserId = null,
            string crossAssesserName = null,
            List<DataCollectorType> dataCollectorTypes = null, DataCollectorType? dataCollectorType = null,
            int limit = 200)
        {
            var query = CreateCriteriaQuery<DeptIndicator>().CreateAlias("t.CrossAssesser", "ca");
            if (departmentIds != null || departmentId.HasValue)
            {
                if (departmentIds == null)
                    departmentIds = new List<Guid>();
                if (departmentId.HasValue)
                    departmentIds.Add(departmentId.Value);
                if (departmentIds.Count > 0)
                    query.Add(Restrictions.In("t.Department.Id", departmentIds.ToArray()));
            }

            BindIndicatorQuery(query, linkedFormIds, linkedFormId, indicatorName, evaluateType, dataSource, discriminant, crossAssesserId, crossAssesserName, dataCollectorTypes, dataCollectorType, limit);

            return query.List<DeptIndicator>();
        }

        private static void BindIndicatorQuery(ICriteria query,
            List<Guid> linkedFormIds = null, Guid? linkedFormId = null,
            string indicatorName = null,
            EvaluateType? evaluateType = null,
            string dataSource = null,
            string discriminant = null,
            Guid? crossAssesserId = null,
            string crossAssesserName = null,
            List<DataCollectorType> dataCollectorTypes = null, DataCollectorType? dataCollectorType = null,
            int limit = 200)
        {
            if (linkedFormIds != null || linkedFormId.HasValue)
            {
                if (linkedFormIds == null)
                    linkedFormIds = new List<Guid>();
                if (linkedFormId.HasValue)
                    linkedFormIds.Add(linkedFormId.Value);
                if (linkedFormIds.Count > 0)
                    query.Add(Restrictions.In("t.Form.Id", linkedFormIds.ToArray()));
            }
            if (!string.IsNullOrWhiteSpace(indicatorName))
            {
                query.Add(Restrictions.Like("t.Name", indicatorName, MatchMode.Anywhere));
            }
            if (evaluateType.HasValue)
            {
                query.Add(Restrictions.Eq("t.EvaluateType", evaluateType));
            }
            if (!string.IsNullOrWhiteSpace(dataSource))
            {
                query.Add(Restrictions.Like("t.DataSource", dataSource, MatchMode.Anywhere));
            }
            if (!string.IsNullOrWhiteSpace(discriminant))
            {
                query.Add(Restrictions.Like("t.Discriminant", discriminant, MatchMode.Anywhere));
            }
            if (!string.IsNullOrWhiteSpace(crossAssesserName))
            {
                query.Add(Restrictions.Like("ca.Name", crossAssesserName, MatchMode.Anywhere));
            }
            if (crossAssesserId.HasValue)
            {
                query.Add(Restrictions.Eq("t.CrossAssesser.Id", crossAssesserId));
            }
            if (dataCollectorTypes != null || dataCollectorType.HasValue)
            {
                if (dataCollectorTypes == null)
                    dataCollectorTypes = new List<DataCollectorType>();
                if (dataCollectorType.HasValue)
                    dataCollectorTypes.Add(dataCollectorType.Value);

                if (dataCollectorTypes.Count > 0)
                    query.Add(Restrictions.In("t.DataCollectorType", dataCollectorTypes.ToArray()));
            }
            query.SetMaxResults(limit);
        }
时间: 2024-10-11 10:35:36

NHibernate查询示例合集的相关文章

知识类API调用的代码示例合集:驾考题库、ISBN书号查询、万年历查询等

以下示例代码适用于 www.apishop.net 网站下的API,使用本文提及的接口调用代码示例前,您需要先申请相应的API服务. 驾考题库:获取驾考题目与答案 ISBN书号查询:通过10位或13位ISBN查询书号信息,包含书名.作者.出版社.价格.出版日期.印次.装帧方式.语种.摘要等信息. 万年历查询:查询指定日期的星期.星座.农历.生肖.天干地支.岁次.黄历相关的福神.喜神.宜忌等信息,还可以进行阴阳历转换. 节假日查询:全年节假日查询 成语大全:包含发音.解释.出自典故.近义词.反义词

验证码识别与生成类API调用的代码示例合集:六位图片验证码生成、四位图片验证码生成、简单验证码识别等

以下示例代码适用于 www.apishop.net 网站下的API,使用本文提及的接口调用代码示例前,您需要先申请相应的API服务. 六位图片验证码生成:包括纯数字.小写字母.大写字母.大小写混合.数字+小写.数字+大写.数字+大小写等情况. 四位图片验证码生成:包括纯数字.小写字母.大写字母.大小写混合.数字+小写.数字+大写.数字+大小写等情况. 简单验证码识别:验证码类型 : 数字+字母, 纯英文, 纯数字,计算题 英数_验证码识别:纯数字,纯英文,数字+英文 中英数_验证码识别:英文.数

影视娱乐类API调用的代码示例合集:NBA赛事、电视节目等

以下示例代码适用于 www.apishop.net 网站下的API,使用本文提及的接口调用代码示例前,您需要先申请相应的API服务. NBA赛事:NBA篮球赛事赛程相关信息 电视节目:央视及各地卫视的电视节目时间表,包括本周及下周的电视节目内容 **API Shop(apishop.net)提供多达50款的常用第三方API,可以从github上下载代码示例合集:https://github.com/apishop/All-APIs** 以上接口均包含PHP.Python.C#和Java等四种语言

FFmpeg示例程序合集-批量编译脚本

此前做了一系列有关FFmpeg的示例程序,组成了<最简单的FFmpeg示例程序合集>,其中包含了如下项目:simplest ffmpeg player:                  最简单的基于FFmpeg的视频播放器simplest ffmpeg audio player:       最简单的基于FFmpeg的音频播放器simplest ffmpeg pic encoder:        最简单的基于FFmpeg的图像编码器simplest ffmpeg video encoder

FFmpeg示例程序合集-Git批量获取脚本

此前做了一系列有关FFmpeg的示例程序,组成了<FFmpeg示例程序合集>,其中包含了如下项目:simplest ffmpeg player:                  最简单的基于FFmpeg的视频播放器simplest ffmpeg audio player:       最简单的基于FFmpeg的音频播放器simplest ffmpeg pic encoder:        最简单的基于FFmpeg的图像编码器simplest ffmpeg video encoder:  

使用 NHibernate 的示例查询

示例查询最多的应用场合是组合查询,我们常常需要在界面上提供若干的查询选项,然后根据用户的输入返回符合条件的结果. 使用代码直接进行处理往往需要涉及到复杂的条件,由于组合条件并不确定,导致逻辑判断语句结构复杂.对于多个可选的参数,情况会变得更加严重. 使用示例查询可以很方便地处理这种问题. 在查询的时候,将收集到的查询条件赋予一个对象的属性,当然,这个对象的类型就是需要查询的实体对象. 例如,在 NHibernate 中存在一个 User 的类型,我们需要对它的姓名和口令进行组合查询,User 的

2014年880个合集Android-实例子源代码文件下载地址合集

***************************************************************************************************优质Android 源码现有各类源码接近6000套,视频教程100套,主要涉及.net网站.软件与安卓系列源码,每套源码都已经经过测试,必须附加使用说明或帮助文档.靠谱不坑爹! 需要打包下载合集地址请的朋友 ,欢迎您与我交流 QQ群: 258450620 或QQ:50841662Android 源代码

机器学习和深度学习资料合集

机器学习和深度学习资料合集 注:机器学习资料篇目一共500条,篇目二开始更新 希望转载的朋友,你可以不用联系我.但是一定要保留原文链接,因为这个项目还在继续也在不定期更新.希望看到文章的朋友能够学到更多.此外:某些资料在中国访问需要梯子. <Brief History of Machine Learning> 介绍:这是一篇介绍机器学习历史的文章,介绍很全面,从感知机.神经网络.决策树.SVM.Adaboost到随机森林.Deep Learning. <Deep Learning in

前端资源教程合集

综合类 前端知识体系 前端知识结构 Web前端开发大系概览 Web前端开发大系概览-中文版 Web Front-end Stack v2.2 En类资源汇总 免费的编程中文书籍索引 前端书籍 前端免费书籍大全 前端知识体系 免费的编程中文书籍索引 智能社 - 精通JavaScript开发 重新介绍 JavaScript(JS 教程) 麻省理工学院公开课:计算机科学及编程导论 JavaScript中的this陷阱的最全收集--没有之一 JS函数式编程指南 JavaScript Promise迷你书