public override string ResolveSelect(int?topNum)
        {
            //添加需要连接的导航表
            var masterEntity   = EntityCache.QueryEntity(abstractSet.TableType);
            var navigationList = masterEntity.Navigations;

            if (navigationList.Any())
            {
                provider.JoinList.AddRange(ExpressionExtension.Clone(navigationList));
            }
            //查询字段解析
            StringBuilder selectSql = new StringBuilder("SELECT");

            //去重
            if (abstractSet.IsDistinct)
            {
                selectSql.Append(" DISTINCT ");
            }

            //不是自定义返回视图则显示所有字段
            if (provider.Context.Set.SelectExpression == null)
            {
                var propertyBuilder = GetTableField(masterEntity);
                selectSql.Append(propertyBuilder);
            }
            else//自定义查询字段
            {
                var selectExp = new SelectExpression(provider.Context.Set.SelectExpression, "", provider);
                selectSql.Append($" {selectExp.SqlCmd} ");
                provider.Params.AddDynamicParams(selectExp.Param);
            }
            return(selectSql.ToString());
        }
        public override string ResolveMax(LambdaExpression selector)
        {
            if (selector == null)
            {
                throw new ArgumentException("selector");
            }
            var selectSql = "";

            switch (selector.NodeType)
            {
            case ExpressionType.Lambda:
            case ExpressionType.MemberAccess:
            {
                EntityObject entityObject = EntityCache.QueryEntity(selector.Parameters[0].Type);
                var          memberName   = selector.Body.GetCorrectPropertyName();
                string       fieldName    = $"{entityObject.AsName}.{providerOption.CombineFieldName(entityObject.FieldPairs[memberName])}";
                selectSql = $" SELECT Max({fieldName})  ";
            }
            break;

            case ExpressionType.MemberInit:
                throw new DapperExtensionException("不支持该表达式类型");
            }

            return(selectSql);
        }
Example #3
0
        /// <summary>
        /// 获取表名称
        /// </summary>
        /// <param name="isNeedFrom"></param>
        /// <param name="isAsName"></param>
        /// <param name="tableType">连接查询时会用到</param>
        /// <returns></returns>

        public string FormatTableName(bool isNeedFrom = true, bool isAsName = true, Type tableType = null)
        {
            var    entity   = EntityCache.QueryEntity(tableType == null ? Context.Set.TableType : tableType);
            string schema   = string.IsNullOrEmpty(entity.Schema) ? "" : ProviderOption.CombineFieldName(entity.Schema) + ".";
            string fromName = entity.Name;
            //函数AsTableName优先级大于一切
            string asTableName;

            if (AsTableNameDic.TryGetValue(entity.Type, out asTableName))
            {
                fromName = asTableName;
            }
            //是否存在实体特性中的AsName标记
            if (isAsName)
            {
                fromName = entity.AsName.Equals(fromName) ? ProviderOption.CombineFieldName(fromName) : $"{ProviderOption.CombineFieldName(fromName)} {entity.AsName}";
            }
            else
            {
                fromName = ProviderOption.CombineFieldName(fromName);
            }
            SqlString = $" {schema}{fromName} ";
            if (isNeedFrom)
            {
                SqlString = " FROM " + SqlString;
            }

            return(SqlString);
        }
        /// <summary>
        /// 解析查询字段
        /// </summary>
        /// <param name="topNum"></param>
        /// <returns></returns>
        public override string ResolveSelect(int?topNum)
        {
            //添加需要连接的导航表
            var masterEntity   = EntityCache.QueryEntity(abstractSet.TableType);
            var navigationList = masterEntity.Navigations;

            if (navigationList.Any())
            {
                provider.JoinList.AddRange(ExpressionExtension.Clone(navigationList));
            }
            //查询字段解析
            var selectFormat = topNum.HasValue ? " SELECT {1} {0} " : " SELECT {0} ";
            var selectSql    = "";

            //不是自定义返回视图则显示所有字段
            if (provider.Context.Set.SelectExpression == null)
            {
                var propertyBuilder = GetTableField(masterEntity);
                selectSql = string.Format(selectFormat, propertyBuilder, $" TOP {topNum} ");
            }
            else//自定义查询字段
            {
                var selectExp = new SelectExpression(provider.Context.Set.SelectExpression, "", provider);
                selectSql = string.Format(selectFormat, selectExp.SqlCmd, $" TOP {topNum} ");
                provider.Params.AddDynamicParams(selectExp.Param);
            }
            return(selectSql);
        }
        protected string[] FormatInsertParamsAndValues <T>(T t, string[] excludeFields = null)
        {
            var paramSqlBuilder = new StringBuilder(64);
            var valueSqlBuilder = new StringBuilder(64);

            var entity     = EntityCache.QueryEntity(t.GetType());
            var properties = entity.Properties;

            var isAppend = false;

            foreach (var propertiy in properties)
            {
                var fieldName   = propertiy.Name;
                var fieldAsName = entity.FieldPairs[propertiy.Name];
                //是否是排除字段
                if (excludeFields != null && (excludeFields.Contains(propertiy.Name) || excludeFields.Contains(fieldAsName)))
                {
                    continue;
                }
                var customAttributes = propertiy.GetCustomAttributess(true);
                //导航属性排除
                if (customAttributes.Any(x => x.GetType().Equals(typeof(ForeignKey))))
                {
                    continue;
                }
                //主键标识
                var typeAttribute = customAttributes.FirstOrDefault(x => x.GetType().Equals(typeof(Identity)));
                if (typeAttribute != null)
                {
                    var identity = typeAttribute as Identity;
                    //是否自增
                    if (identity.IsIncrease)
                    {
                        continue;
                    }
                }
                //排除掉时间格式为最小值的字段
                if (propertiy.PropertyType == typeof(DateTime))
                {
                    if (Convert.ToDateTime(propertiy.GetValue(t)) == DateTime.MinValue)
                    {
                        continue;
                    }
                }
                if (isAppend)
                {
                    paramSqlBuilder.Append(",");
                    valueSqlBuilder.Append(",");
                }
                var name = propertiy.GetColumnAttributeName();
                paramSqlBuilder.AppendFormat("{0}{1}{2}", ProviderOption.OpenQuote, fieldAsName, ProviderOption.CloseQuote);
                valueSqlBuilder.Append(ProviderOption.ParameterPrefix + name);
                Params.Add(ProviderOption.ParameterPrefix + name, propertiy.GetValue(t));
                isAppend = true;
            }
            return(new[] { paramSqlBuilder.ToString(), valueSqlBuilder.ToString() });
        }
        public override SqlProvider FormatUpdateSelect <T>(Expression <Func <T, T> > updator)
        {
            var update = ResolveExpression.ResolveUpdate(updator);

            var selectSql = ResolveExpression.ResolveSelectOfUpdate(EntityCache.QueryEntity(typeof(T)), Context.Set.SelectExpression);

            var whereSql = ResolveExpression.ResolveWhereList();

            Params.AddDynamicParams(update.Param);

            SqlString = $"UPDATE {FormatTableName(false, false)} {update.SqlCmd} {selectSql} {whereSql}";

            return(this);
        }
Example #7
0
        /// <summary>
        /// 根据主键获取条件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public virtual string GetIdentityWhere <T>(object id, DynamicParameters param = null)
        {
            var entityObject = EntityCache.QueryEntity(typeof(T));

            if (string.IsNullOrEmpty(entityObject.Identitys))
            {
                throw new DapperExtensionException("主键不存在!请前往实体类使用[Identity]特性设置主键。");
            }

            //设置参数
            if (param != null)
            {
                param.Add(entityObject.Identitys, id);
            }
            return($" AND {entityObject.Identitys}={ProviderOption.ParameterPrefix}{entityObject.Identitys} ");
        }
Example #8
0
        /// <summary>
        /// 根据主键获取条件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        protected string GetIdentityWhere <T>(T entity, DynamicParameters param)
        {
            var entityObject = EntityCache.QueryEntity(typeof(T));

            if (string.IsNullOrEmpty(entityObject.Identitys))
            {
                throw new DapperExtensionException("主键不存在!请前往实体类使用[Identity]特性设置主键。");
            }
            //获取主键数据
            var id = entityObject.Properties
                     .FirstOrDefault(x => x.Name == entityObject.Identitys)
                     .GetValue(entity);

            //设置参数
            param.Add(entityObject.Identitys, id);
            return($" AND {entityObject.Identitys}={ProviderOption.ParameterPrefix}{entityObject.Identitys} ");
        }
Example #9
0
        /// <summary>
        /// 根据主键获取条件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public virtual string GetIdentityWhere <T>(T entity, DynamicParameters param = null)
        {
            var entityObject = EntityCache.QueryEntity(typeof(T));

            if (string.IsNullOrEmpty(entityObject.Identitys))
            {
                throw new DapperExtensionException("主键不存在!请前往实体类使用[Identity]特性设置主键。");
            }

            //设置参数
            if (param != null)
            {
                //获取主键数据
                var id = entityObject.EntityFieldList
                         .FirstOrDefault(x => x.FieldName == entityObject.Identitys)
                         .PropertyInfo
                         .GetValue(entity);
                param.Add(entityObject.Identitys, id);
            }
            return($" AND {entityObject.Identitys}={ProviderOption.ParameterPrefix}{entityObject.Identitys} ");
        }
        protected string[] FormatInsertParamsAndValues <T>(T t)
        {
            var paramSqlBuilder = new StringBuilder(64);
            var valueSqlBuilder = new StringBuilder(64);

            var entity     = EntityCache.QueryEntity(t.GetType());
            var properties = entity.Properties;

            var isAppend = false;

            foreach (var propertiy in properties)
            {
                //主键标识
                var typeAttribute = propertiy.GetCustomAttributess(true).FirstOrDefault(x => x.GetType().Equals(typeof(Identity)));
                if (typeAttribute != null)
                {
                    var identity = typeAttribute as Identity;
                    //是否自增
                    if (identity.IsIncrease)
                    {
                        continue;
                    }
                }
                if (isAppend)
                {
                    paramSqlBuilder.Append(",");
                    valueSqlBuilder.Append(",");
                }
                var name = propertiy.GetColumnAttributeName();
                paramSqlBuilder.AppendFormat("{0}{1}{2}", ProviderOption.OpenQuote, entity.FieldPairs[name], ProviderOption.CloseQuote);
                valueSqlBuilder.Append(ProviderOption.ParameterPrefix + name);
                Params.Add(ProviderOption.ParameterPrefix + name, propertiy.GetValue(t));
                isAppend = true;
            }
            return(new[] { paramSqlBuilder.ToString(), valueSqlBuilder.ToString() });
        }
Example #11
0
        /// <summary>
        /// 自定义条件生成表达式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dynamicTree"></param>
        /// <returns></returns>
        public virtual IEnumerable <LambdaExpression> FormatDynamicTreeWhereExpression <T>(Dictionary <string, DynamicTree> dynamicTree)
        {
            foreach (var key in dynamicTree.Keys)
            {
                DynamicTree tree = dynamicTree[key];
                if (tree != null && !string.IsNullOrEmpty(tree.Value))
                {
                    Type tableType = typeof(T);
                    if (!string.IsNullOrEmpty(tree.Table))
                    {
                        tableType = EntityCache.QueryEntity(tree.Table).Type;
                    }
                    //如果不存在对应表就使用默认表
                    ParameterExpression param = Expression.Parameter(tableType, "param");
                    object value = tree.Value;
                    if (value == null)
                    {
                        continue;
                    }
                    else if (tree.ValueType == DbType.DateTime)
                    {
                        value = Convert.ToDateTime(value);
                    }
                    else if (tree.ValueType == DbType.String)
                    {
                        value = Convert.ToString(value);
                        if ("" == value.ToString())
                        {
                            continue;
                        }
                    }
                    else if (tree.ValueType == DbType.Int32)
                    {
                        int number = Convert.ToInt32(value);
                        value = number;
                        if (0 == number)
                        {
                            continue;
                        }
                    }
                    else if (tree.ValueType == DbType.Boolean)
                    {
                        if (value.ToString() == "")
                        {
                            continue;
                        }
                        value = Convert.ToBoolean(value);
                    }
                    Expression whereExpress = null;
                    switch (tree.Operators)
                    {
                    case ExpressionType.Equal:    //等于
                        whereExpress = Expression.Equal(Expression.Property(param, tree.Field), Expression.Constant(value));
                        break;

                    case ExpressionType.GreaterThanOrEqual:    //大于等于
                        whereExpress = Expression.GreaterThanOrEqual(Expression.Property(param, tree.Field), Expression.Constant(value));
                        break;

                    case ExpressionType.LessThanOrEqual:    //小于等于
                        whereExpress = Expression.LessThanOrEqual(Expression.Property(param, tree.Field), Expression.Constant(value));
                        break;

                    case ExpressionType.Call:    //模糊查询
                        var method = typeof(string).GetMethodss().FirstOrDefault(x => x.Name.Equals("Contains"));
                        whereExpress = Expression.Call(Expression.Property(param, tree.Field), method, new Expression[] { Expression.Constant(value) });
                        break;

                    default:
                        whereExpress = Expression.Equal(Expression.Property(param, tree.Field), Expression.Constant(value));
                        break;
                    }
                    var lambdaExp = Expression.Lambda(TrimExpression.Trim(whereExpress), param);
                    //WhereExpressionList.Add();
                    yield return(lambdaExp);
                }
            }
        }