Beispiel #1
0
        public string QuerySqlBuild(out IQueryParameters parameters)
        {
            string sql;

            parameters = new QueryParameters();

            //分页查询
            if (_queryBody.Take > 0)
            {
                var select = ResolveSelect();
                var from   = ResolveFrom(parameters);
                var where = ResolveWhere(parameters);
                var sort = ResolveOrder();

                #region ==SqlServer分页需要指定排序==

                //SqlServer分页需要指定排序,此处判断是否有主键,有主键默认按照主键排序
                if (_sqlAdapter.SqlDialect == SqlDialect.SqlServer && StringExtensions.IsNull(sort))
                {
                    var first = _queryBody.JoinDescriptors.First();
                    if (first.EntityDescriptor.PrimaryKey.IsNo())
                    {
                        throw new Exception("SqlServer数据库没有主键的表需要指定排序字段才可以分页查询");
                    }

                    if (_queryBody.JoinDescriptors.Count > 1)
                    {
                        sort = $"{_sqlAdapter.AppendQuote(first.Alias)}.{_sqlAdapter.AppendQuote(first.EntityDescriptor.PrimaryKey.Name)}";
                    }
                    else
                    {
                        sort = first.EntityDescriptor.PrimaryKey.Name;
                    }
                }

                #endregion

                sql = _sqlAdapter.GeneratePagingSql(select, from, where, sort, _queryBody.Skip, _queryBody.Take);
            }
            else
            {
                var sqlBuilder = new StringBuilder("SELECT ");

                ResolveSelect(sqlBuilder);

                sqlBuilder.Append(" FROM ");

                ResolveFrom(sqlBuilder, parameters);

                ResolveWhere(sqlBuilder, parameters);

                ResolveOrder(sqlBuilder);

                sql = sqlBuilder.ToString();
            }

            _logger?.LogDebug("Query:{0}", sql);

            return(sql);
        }
Beispiel #2
0
        private void ResolveOrder(StringBuilder sqlBuilder)
        {
            var sql = ResolveOrder();

            if (StringExtensions.NotNull(sql))
            {
                sqlBuilder.AppendFormat(" ORDER BY {0}", sql);
            }
        }