/// <summary>
        /// 解析表达式
        /// </summary>
        /// <param name="re">当前解析对象</param>
        /// <param name="exp">要解析的表达式</param>
        public void ResolveExpression(ResolveExpress re, Expression exp)
        {
            //初始化表达式
            Init(re, exp);

            //设置PageSize
            foreach (var par in Paras)
            {
                SqlSugarTool.SetParSize(par);
            }
        }
Beispiel #2
0
        public void ResolveExpression(ResolveExpress re, Expression exp)
        {
            ResolveExpress.MemberType type = ResolveExpress.MemberType.None;
            var expStr        = exp.ToString();
            var isNotBool     = !expStr.Contains("True") && !expStr.Contains("False");
            var isContainsNot = expStr.Contains("Not");

            if (isContainsNot && expStr.IsMatch(@" => Not\(.+?\)") && !expStr.Contains("Contains"))
            {
                this.SqlWhere = string.Format(" AND {0}=0 or {0} is null ", Regex.Match(expStr, @" => Not\(.+\.(.+?)\)").Groups[1].Value);
            }
            else if (isNotBool)
            {
                this.SqlWhere = string.Format(" AND {0} ", re.CreateSqlElements(exp, ref type));
            }
            else
            {
                var isTrue  = Regex.IsMatch(expStr, @"\=\> True$");
                var isFalse = Regex.IsMatch(expStr, @"\=\> False$");
                if (isFalse)
                {
                    this.SqlWhere = string.Format(" AND 1<>1 ");
                }
                else if (isTrue)
                {
                }
                else
                {
                    this.SqlWhere = string.Format(" AND {0} ", re.CreateSqlElements(exp, ref type));
                }
            }
            foreach (var par in Paras)
            {
                SqlSugarTool.SetParSize(par);
            }
        }
Beispiel #3
0
        /// <summary>
        /// 更新
        /// 注意:rowObj为T类型将更新该实体的非主键所有列,如果rowObj类型为匿名类将更新指定列
        /// 使用说明:sqlSugar.Update《T》(rowObj,whereObj);
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="rowObj">new T(){name="张三",sex="男"}或者new {name="张三",sex="男"}</param>
        /// <param name="expression">it.id=100</param>
        /// <returns></returns>
        public bool Update <T>(object rowObj, Expression <Func <T, bool> > expression) where T : class
        {
            if (rowObj == null)
            {
                throw new ArgumentNullException("SqlSugarClient.Update.rowObj");
            }
            if (expression == null)
            {
                throw new ArgumentNullException("SqlSugarClient.Update.expression");
            }


            Type   type     = typeof(T);
            string typeName = type.Name;

            typeName = GetTableNameByClassType(typeName);
            var rows = SqlSugarTool.GetParameters(rowObj);

            //sql语句缓存
            string cacheSqlKey     = "db.update." + typeName + rows.Length;
            var    cacheSqlManager = CacheManager <StringBuilder> .GetInstance();



            string pkName        = SqlSugarTool.GetPrimaryKeyByTableName(this, typeName);
            var    identityNames = SqlSugarTool.GetIdentitiesKeyByTableName(this, typeName);


            ResolveExpress re = new ResolveExpress();

            re.ResolveExpression(re, expression);


            StringBuilder sbSql = new StringBuilder();

            if (cacheSqlManager.ContainsKey(cacheSqlKey))
            {
                sbSql = cacheSqlManager[cacheSqlKey];
            }
            else
            {
                sbSql = new StringBuilder(string.Format(" UPDATE [{0}] SET ", typeName));
                foreach (var r in rows)
                {
                    var name                   = r.ParameterName.TrimStart('@');
                    var isPk                   = pkName != null && pkName.ToLower() == name.ToLower();
                    var isIdentity             = identityNames.Any(it => it.Value.ToLower() == name.ToLower());
                    var isDisableUpdateColumns = DisableUpdateColumns != null && DisableUpdateColumns.Any(it => it.ToLower() == name.ToLower());
                    if (isPk || isIdentity || isDisableUpdateColumns)
                    {
                        if (rowObj.GetType() == type)
                        {
                            continue;
                        }
                    }
                    sbSql.Append(string.Format(" [{0}] =@{0}  ,", name));
                }
                sbSql.Remove(sbSql.Length - 1, 1);
                sbSql.Append(" WHERE  1=1  ");
                sbSql.Append(re.SqlWhere);;
                cacheSqlManager.Add(cacheSqlKey, sbSql, cacheSqlManager.Day);
            }

            List <SqlParameter> parsList = new List <SqlParameter>();

            parsList.AddRange(re.Paras);
            var pars = rows;

            if (pars != null)
            {
                foreach (var par in pars)
                {
                    if (par.SqlDbType == SqlDbType.Udt)
                    {
                        par.UdtTypeName = "HIERARCHYID";
                    }
                    SqlSugarTool.SetParSize(par);
                    parsList.Add(par);
                }
            }
            try
            {
                var updateRowCount = ExecuteCommand(sbSql.ToString(), parsList.ToArray());
                return(updateRowCount > 0);
            }
            catch (Exception ex)
            {
                var cacheManager = CacheManager <string> .GetInstance();

                cacheManager.RemoveAll(it => it.Contains("KeyBy"));
                throw new Exception("sql:" + sbSql.ToString() + "\n" + ex.Message);
            }
        }
Beispiel #4
0
        /// <summary>
        /// 插入
        /// 使用说明:sqlSugar.Insert(entity);
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity">插入对象</param>
        /// <param name="isIdentity">该属性已经作废可以不填,主键是否为自增长,true可以不填,false必填</param>
        /// <returns></returns>
        public object Insert <T>(T entity, bool isIdentity = true) where T : class
        {
            Type   type     = entity.GetType();
            string typeName = type.Name;

            typeName = GetTableNameByClassType(typeName);

            StringBuilder       sbInsertSql = new StringBuilder();
            List <SqlParameter> pars        = new List <SqlParameter>();
            var identities = SqlSugarTool.GetIdentitiesKeyByTableName(this, typeName);

            isIdentity = identities != null && identities.Count > 0;
            //sql语句缓存
            string cacheSqlKey     = "db.Insert." + typeName;
            var    cacheSqlManager = CacheManager <StringBuilder> .GetInstance();

            //属性缓存
            string cachePropertiesKey     = "db." + typeName + ".GetProperties";
            var    cachePropertiesManager = CacheManager <PropertyInfo[]> .GetInstance();

            PropertyInfo[] props = null;
            if (cachePropertiesManager.ContainsKey(cachePropertiesKey))
            {
                props = cachePropertiesManager[cachePropertiesKey];
            }
            else
            {
                props = type.GetProperties();
                cachePropertiesManager.Add(cachePropertiesKey, props, cachePropertiesManager.Day);
            }
            var isContainCacheSqlKey = cacheSqlManager.ContainsKey(cacheSqlKey);

            if (isContainCacheSqlKey)
            {
                sbInsertSql = cacheSqlManager[cacheSqlKey];
            }
            else
            {
                //2.获得实体的属性集合


                //实例化一个StringBuilder做字符串的拼接


                sbInsertSql.Append("insert into [" + typeName + "] (");

                //3.遍历实体的属性集合
                foreach (PropertyInfo prop in props)
                {
                    //EntityState,@EntityKey
                    if (!isIdentity || identities.Any(it => it.Value.ToLower() != prop.Name.ToLower()))
                    {
                        //4.将属性的名字加入到字符串中
                        sbInsertSql.Append("[" + prop.Name + "],");
                    }
                }
                //**去掉最后一个逗号
                sbInsertSql.Remove(sbInsertSql.Length - 1, 1);
                sbInsertSql.Append(" ) values(");
            }

            //5.再次遍历,形成参数列表"(@xx,@xx@xx)"的形式
            foreach (PropertyInfo prop in props)
            {
                //EntityState,@EntityKey
                if (!isIdentity || identities.Any(it => it.Value.ToLower() != prop.Name.ToLower()))
                {
                    if (!cacheSqlManager.ContainsKey(cacheSqlKey))
                    {
                        sbInsertSql.Append("@" + prop.Name + ",");
                    }
                    object val = prop.GetValue(entity, null);
                    if (val == null)
                    {
                        val = DBNull.Value;
                    }
                    if (_serialNumber.IsValuable())
                    {
                        Func <PubModel.SerialNumber, bool> serEexp = it => it.TableName.ToLower() == typeName.ToLower() && it.FieldName.ToLower() == prop.Name.ToLower();
                        var isAnyNum = _serialNumber.Any(serEexp);
                        if (isAnyNum && (val == DBNull.Value || val.IsNullOrEmpty()))
                        {
                            val = _serialNumber.First(serEexp).GetNumFunc();
                        }
                    }

                    if (prop.PropertyType.IsEnum)
                    {
                        val = (int)(val);
                    }

                    var par = new SqlParameter("@" + prop.Name, val);
                    SqlSugarTool.SetParSize(par);
                    if (par.SqlDbType == SqlDbType.Udt)
                    {
                        par.UdtTypeName = "HIERARCHYID";
                    }
                    pars.Add(par);
                }
            }
            if (!isContainCacheSqlKey)
            {
                //**去掉最后一个逗号
                sbInsertSql.Remove(sbInsertSql.Length - 1, 1);
                if (isIdentity == false)
                {
                    sbInsertSql.Append(");select 'true';");
                }
                else
                {
                    sbInsertSql.Append(");select SCOPE_IDENTITY();");
                }
                cacheSqlManager.Add(cacheSqlKey, sbInsertSql, cacheSqlManager.Day);
            }
            var sql = sbInsertSql.ToString();

            try
            {
                var lastInsertRowId = GetScalar(sql, pars.ToArray());
                return(lastInsertRowId);
            }
            catch (Exception ex)
            {
                var cacheManager = CacheManager <string> .GetInstance();

                cacheManager.RemoveAll(it => it.Contains("KeyBy"));
                throw new Exception("sql:" + sql + "\n" + ex.Message);
            }
        }