Ejemplo n.º 1
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} ");
        }
Ejemplo n.º 2
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} ");
        }
Ejemplo n.º 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)
            {
                if (entity.AsName.Equals(fromName))
                {
                    fromName = ProviderOption.CombineFieldName(fromName);
                }
                else
                {
                    //加上as标记
                    fromName = $"{ProviderOption.CombineFieldName(fromName)} {entity.AsName}";
                }
            }
            else
            {
                fromName = ProviderOption.CombineFieldName(fromName);
            }
            string sqlString = $" {schema}{fromName} ";

            //是否需要FROM
            if (isNeedFrom)
            {
                sqlString = $" FROM {sqlString}";
            }
            return(sqlString);
        }
		/// <summary>
		/// 解析查询最大值
		/// </summary>
		/// <param name="selector"></param>
		/// <returns></returns>
		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();
						selectSql = $" SELECT Max({entityObject.AsName}.{providerOption.CombineFieldName(entityObject.FieldPairs[memberName])})  ";
					}
					break;
				case ExpressionType.MemberInit:
					throw new DapperExtensionException("不支持该表达式类型");
			}

			return selectSql;
		}
        /// <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));
            }
            //查询字段解析
            StringBuilder selectSql = new StringBuilder(" SELECT ");

            ////去重
            //if (abstractSet.IsDistinct)
            //	selectSql.Append(" DISTINCT ");
            //top
            if (topNum.HasValue)
            {
                selectSql.Append($" TOP {topNum} ");
            }
            //else
            //	//设置返回百分比(为了兼容更多语法)
            //	selectSql.Append(" TOP (100) PERCENT ");
            //不是自定义返回视图则显示所有字段
            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());
        }
        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() });
        }
Ejemplo n.º 7
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);
                }
            }
        }