Example #1
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="whereIn">new int[]{1,2,3}</param>
        /// <returns></returns>
        public bool Update <T, FiledType>(object rowObj, params FiledType[] whereIn) where T : class
        {
            if (rowObj == null)
            {
                throw new ArgumentNullException("SqlSugarClient.Update.rowObj");
            }

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

            typeName = GetTableNameByClassType(typeName);
            StringBuilder sbSql = new StringBuilder(string.Format(" UPDATE {0} SET ", typeName));
            Dictionary <string, object> rows = SqlSugarTool.GetObjectToDictionary(rowObj);
            string pkName        = SqlSugarTool.GetPrimaryKeyByTableName(this, typeName);
            var    identityNames = SqlSugarTool.GetIdentitiesKeyByTableName(this, typeName);

            foreach (var r in rows)
            {
                var isPk                   = pkName != null && pkName.ToLower() == r.Key.ToLower();
                var isIdentity             = identityNames.Any(it => it.Value.ToLower() == r.Key.ToLower());
                var isDisableUpdateColumns = DisableUpdateColumns != null && DisableUpdateColumns.Any(it => it.ToLower() == r.Key.ToLower());
                if (isPk || isIdentity || isDisableUpdateColumns)
                {
                    if (rowObj.GetType() == type)
                    {
                        continue;
                    }
                }
                sbSql.Append(string.Format(" [{0}] =@{0}  ,", r.Key));
            }
            sbSql.Remove(sbSql.Length - 1, 1);
            if (whereIn.Count() == 0)
            {
                var value = type.GetProperties().Cast <PropertyInfo>().Single(it => it.Name == pkName).GetValue(rowObj, null);
                sbSql.AppendFormat("WHERE {1} IN ('{2}')", typeName, pkName, value);
            }
            else
            {
                sbSql.AppendFormat("WHERE {1} IN ({2})", typeName, pkName, whereIn.ToJoinSqlInVal());
            }
            List <SQLiteParameter> parsList = new List <SQLiteParameter>();
            var pars = rows.Select(c => new SQLiteParameter("@" + c.Key, c.Value));

            if (pars != null)
            {
                foreach (var par in pars)
                {
                    var isDisableUpdateColumns = DisableUpdateColumns != null && DisableUpdateColumns.Any(it => it.ToLower() == par.ParameterName.TrimStart('@').ToLower());
                    if (!isDisableUpdateColumns)
                    {
                        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);
            }
        }
Example #2
0
        /// <summary>
        /// 批量假删除
        /// 使用说明::
        /// FalseDelete《T》("is_del",new int[]{1,2,3})或者Delete《T》("is_del",3)
        /// </summary>
        /// <param name="field">更新删除状态字段</param>
        /// <param name="whereIn">delete ids</param>
        public bool FalseDelete <T, FiledType>(string field, params FiledType[] whereIn)
        {
            Type   type     = typeof(T);
            string typeName = type.Name;

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

            PropertyInfo[] props     = SqlSugarTool.GetGetPropertiesByCache(type, cachePropertiesKey, cachePropertiesManager);
            bool           isSuccess = false;

            if (whereIn != null && whereIn.Length > 0)
            {
                string sql            = string.Format("UPDATE  {0} SET {3}=1 WHERE {1} IN ({2})", typeName, SqlSugarTool.GetPrimaryKeyByTableName(this, typeName), whereIn.ToJoinSqlInVal(), field);
                int    deleteRowCount = ExecuteCommand(sql);
                isSuccess = deleteRowCount > 0;
            }
            return(isSuccess);
        }
Example #3
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 <SQLiteParameter> pars        = new List <SQLiteParameter>();
            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 SQLiteParameter("@" + prop.Name, val);
                    SqlSugarTool.SetParSize(par);

                    pars.Add(par);
                }
            }
            if (!isContainCacheSqlKey)
            {
                //**去掉最后一个逗号
                sbInsertSql.Remove(sbInsertSql.Length - 1, 1);
                if (isIdentity == false)
                {
                    sbInsertSql.Append(");select 'true';");
                }
                else
                {
                    sbInsertSql.Append(");select  last_insert_rowid() newid;");
                }
                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);
            }
        }
Example #4
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);
            StringBuilder sbSql  = new StringBuilder(string.Format(" UPDATE {0} SET ", typeName));
            var           rows   = SqlSugarTool.GetParameters(rowObj);
            string        pkName = SqlSugarTool.GetPrimaryKeyByTableName(this, typeName);

            foreach (var r in rows)
            {
                if (pkName == r.ParameterName.TrimStart('@'))
                {
                    if (rowObj.GetType() == type)
                    {
                        continue;
                    }
                }
                sbSql.Append(string.Format(" [{0}] =@{0}  ,", r.ParameterName.TrimStart('@')));
            }
            sbSql.Remove(sbSql.Length - 1, 1);
            sbSql.Append(" WHERE  1=1  ");
            ResolveExpress re = new ResolveExpress();

            re.ResolveExpression(re, expression);
            sbSql.Append(re.SqlWhere);;

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

            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);
            }
        }
Example #5
0
 public int GetInt(string sql, object pars)
 {
     return(GetInt(sql, SqlSugarTool.GetParameters(pars)));
 }
Example #6
0
        /// <summary>
        /// 根据SQL语句将结果集映射到List《T》
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="whereObj"></param>
        /// <returns></returns>
        public List <T> SqlQuery <T>(string sql, object whereObj = null)
        {
            var pars = SqlSugarTool.GetParameters(whereObj).ToList();

            return(SqlQuery <T>(sql, pars));
        }
Example #7
0
 public DataSet GetDataSetAll(string sql, object pars)
 {
     return(GetDataSetAll(sql, SqlSugarTool.GetParameters(pars)));
 }
Example #8
0
 public string GetString(string sql, object pars)
 {
     return(GetString(sql, SqlSugarTool.GetParameters(pars)));
 }
Example #9
0
        public T GetSingle <T>(string sql, params SQLiteParameter[] pars)
        {
            var reval = SqlSugarTool.DataReaderToList <T>(typeof(T), GetReader(sql, pars), null).Single();

            return(reval);
        }
Example #10
0
 public DataTable GetDataTable(string sql, object pars)
 {
     return(GetDataTable(sql, SqlSugarTool.GetParameters(pars)));
 }
Example #11
0
 public T GetSingle <T>(string sql, object[] pars)
 {
     return(GetSingle <T>(sql, SqlSugarTool.GetParameters(pars)));
 }
Example #12
0
 public List <T> GetList <T>(string sql, object pars)
 {
     return(GetList <T>(sql, SqlSugarTool.GetParameters(pars)));
 }
Example #13
0
 public SQLiteDataReader GetReader(string sql, object pars)
 {
     return(GetReader(sql, SqlSugarTool.GetParameters(pars)));
 }
Example #14
0
 public int ExecuteCommand(string sql, object pars)
 {
     return(ExecuteCommand(sql, SqlSugarTool.GetParameters(pars)));
 }
Example #15
0
 public object GetScalar(string sql, object pars)
 {
     return(GetScalar(sql, SqlSugarTool.GetParameters(pars)));
 }