Пример #1
0
        /// <summary>
        /// 从一个对象实例中通过检查DbTable和DbField特性来构建一个用于插入数据行的T-SQL语句。
        /// 为了防止SQL注入,该SQL语句是参数化的,并且通过out参数返回由entity对象实例中包括的值构建出来的SqlParameter集
        /// </summary>
        /// <param name="entity">准备用作插入新行的对象实例</param>
        /// <param name="parameters">参数化的每一列输入参数,包含了值</param>
        /// <param name="primaryKey">主键输出参数,用来返回新行的主键</param>
        /// <returns></returns>
        static string BuildInsertSql(object entity, out SqlParameter[] parameters, out SqlParameter primaryKey)
        {
            Type type = entity.GetType();

            object[] tableAttributes = type.GetCustomAttributes(typeof(DbTableAttribute), false);
            if (tableAttributes == null || tableAttributes.Length != 1)
            {
                throw new Exception("使用BuildInsertSql()方法,类" + type.FullName + "必须标记唯一的DbTable特性。");
            }

            DbTableAttribute tableAttr = (DbTableAttribute)tableAttributes[0];

            StringBuilder       fieldBuilder = new StringBuilder(), valueBuilder = new StringBuilder();
            List <SqlParameter> parametersList = new List <SqlParameter>();

            primaryKey = null;
            foreach (MemberInfo m in type.GetMembers(BindingFlags.Instance | BindingFlags.Public))
            {
                #region loop values
                bool isDefine = m.IsDefined(typeof(DbFieldAttribute), false);
                if (!isDefine)
                {
                    continue;
                }

                DbFieldAttribute fldAttr = (DbFieldAttribute)(DbFieldAttribute.GetCustomAttribute(m, typeof(DbFieldAttribute)));
                if (fldAttr.IsPrimaryKey)
                {
                    primaryKey = new SqlParameter("@" + fldAttr.FieldName, SqlDbType.Int)
                    {
                        Direction = ParameterDirection.Output
                    };
                    parametersList.Add(primaryKey);
                    continue;
                }

                if ((fldAttr.Usage & DbFieldUsage.InsertParameter) != DbFieldUsage.InsertParameter)
                {
                    continue;
                }

                fieldBuilder.Append(",[" + fldAttr.FieldName + "]");
                valueBuilder.Append(",@" + fldAttr.FieldName);

                Type         memberType;
                object       memberValue = ValueHelper.GetMemberValue(m, fldAttr, entity, out memberType);
                SqlParameter parameter   = GenerateSqlParameter(fldAttr, memberType, memberValue);
                parametersList.Add(parameter);
                #endregion
            }
            fieldBuilder.Remove(0, 1);
            valueBuilder.Remove(0, 1);

            string sql = @$ "
INSERT INTO {tableAttr.TableName}({fieldBuilder.ToString()}) VALUES({valueBuilder.ToString()});
Пример #2
0
        /// <summary>
        /// 使用关键字id从数据库中查找,返回entityType类的实例
        /// </summary>
        /// <param name="connector"></param>
        /// <param name="entityType"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static async Task <T> FindEntity <T>(DbConnector connector, int id) where T : new()
        {
            Type entityType = typeof(T);

            object[] tableAttributes = entityType.GetCustomAttributes(typeof(DbTableAttribute), false);
            if (tableAttributes == null || tableAttributes.Length != 1)
            {
                throw new Exception("使用FindEntity()方法,类" + entityType.FullName + "必须标记唯一的DbTable特性。");
            }

            DbTableAttribute tableAttr = (DbTableAttribute)tableAttributes[0];
            string           tableName = tableAttr.TableName;
            string           keyName   = string.Empty;

            foreach (PropertyInfo propertyInfo in entityType.GetProperties())
            {
                if (!propertyInfo.IsDefined(typeof(DbFieldAttribute), false))
                {
                    continue;
                }

                DbFieldAttribute fldAttr = (DbFieldAttribute)(DbFieldAttribute.GetCustomAttribute(propertyInfo, typeof(DbFieldAttribute)));
                if (fldAttr.IsPrimaryKey)
                {
                    keyName = fldAttr.FieldName;
                    break;
                }
            }

            string sql = string.Format(@"SELECT * FROM {0} WHERE {1}={2};", tableName, keyName, id);

            DataTable table = await connector.ExecuteSqlQueryTable(sql);

            if (table == null || table.Rows.Count == 0)
            {
                return(default(T));
            }
            else
            {
                object obj = Activator.CreateInstance(entityType);
                ValueHelper.FulfillEntity(entityType, table.Rows[0], ref obj);
                return((T)obj);
            }
        }
Пример #3
0
        /// <summary>
        /// 使用row中的值填充对象entity
        /// </summary>
        /// <param name="type"></param>
        /// <param name="row"></param>
        /// <param name="entity"></param>
        public static void FulfillEntity(Type type, DataRow row, ref object entity)
        {
            foreach (MemberInfo m in type.GetMembers(BindingFlags.Instance | BindingFlags.Public))
            {
                Attribute attr = DbFieldAttribute.GetCustomAttribute(m, typeof(DbFieldAttribute));
                if (attr == null)
                {
                    continue;
                }

                DbFieldAttribute dAttr = (DbFieldAttribute)attr;
                if ((dAttr.Usage & DbFieldUsage.MapResultTable) != DbFieldUsage.MapResultTable)
                {
                    continue;
                }

                try
                {
                    if (m.MemberType == MemberTypes.Field)
                    {
                        //the member is a DbField;
                        object value = ValueHelper.GetTableRowValue(row, dAttr.FieldName, ((FieldInfo)m).FieldType);
                        ((FieldInfo)m).SetValue(entity, value);
                    }
                    else if (m.MemberType == MemberTypes.Property)
                    {
                        //the member is a DbField;
                        object value = GetTableRowValue(row, dAttr.FieldName, ((PropertyInfo)m).PropertyType);
                        ((PropertyInfo)m).SetValue(entity, value, null);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("成员[" + m.Name + "]出错" + ex.ToString());
                }
            }
        }
Пример #4
0
        /// <summary>
        /// 使用提供的条件查询数据库(表由entityType指定),返回满足条件的记录(分页)
        /// </summary>
        /// <typeparam name="T">要查询的实体类型,标记了DbTable和DbField特性的类,并且具有空白构造函数</typeparam>
        /// <param name="connector"></param>
        /// <param name="criteria">查询条件字典,键是PropertyName,条件仅支持=比较,条件间仅支持AND运算</param>
        /// <param name="pageIndex">从0开始的返回页索引</param>
        /// <param name="pageSize">每页几行记录</param>
        /// <param name="sortProperty">用于排序的PropertyName(如为空则使用关键字)</param>
        /// <param name="descending">是否倒序排列</param>
        /// <param name="total">符合条件的记录总数</param>
        /// <returns></returns>
        public static async Task <PagedQuery <T> > SearchEntities <T>(DbConnector connector, Dictionary <string, object> criteria,
                                                                      int pageIndex, int pageSize, string sortProperty, bool descending) where T : new()
        {
            Type entityType = typeof(T);

            if (!(DbTableAttribute.GetCustomAttribute(entityType, typeof(DbTableAttribute)) is DbTableAttribute tableAttr))
            {
                throw new Exception("类型" + entityType.FullName + "没有标记DbTableAttribute特性");
            }

            string selectClause = "SELECT * ";
            string fromClause   = "FROM " + tableAttr.TableName;
            string orderBy;

            #region 正确处理orderBy
            DbFieldAttribute sortFieldAttr = null;
            if (string.IsNullOrWhiteSpace(sortProperty))
            {
                //如果没有传递sortProperty参数, 则使用PrimaryKey
                foreach (PropertyInfo property in entityType.GetProperties())
                {
                    DbFieldAttribute fldAttr = DbFieldAttribute.GetCustomAttribute(property, typeof(DbFieldAttribute)) as DbFieldAttribute;
                    if (fldAttr != null && fldAttr.IsPrimaryKey)
                    {
                        sortFieldAttr = fldAttr;
                        break;
                    }
                }
            }
            else
            {
                PropertyInfo property = entityType.GetProperty(sortProperty);
                if (property == null)
                {
                    throw new Exception(string.Format("类型{0}中没有找到{1}属性用于排序", entityType.FullName, sortProperty));
                }
                sortFieldAttr = DbFieldAttribute.GetCustomAttribute(property, typeof(DbFieldAttribute)) as DbFieldAttribute;
            }
            if (sortFieldAttr == null)
            {
                throw new Exception("类型" + entityType.FullName + "没有标记IsPrimaryKey=true的DbField特性");
            }

            if (descending)
            {
                orderBy = sortFieldAttr.FieldName + " DESC";
            }
            else
            {
                orderBy = sortFieldAttr.FieldName;
            }
            #endregion

            StringBuilder       whereBuilder  = new StringBuilder();
            List <SqlParameter> sqlParameters = new List <SqlParameter>();
            if (criteria != null)
            {
                foreach (string conditionName in criteria.Keys)
                {
                    if (criteria[conditionName] == null || criteria[conditionName].ToString().Length == 0)
                    {
                        continue;
                    }

                    PropertyInfo conditionProperty = entityType.GetProperty(conditionName);
                    if (conditionProperty == null)
                    {
                        throw new Exception(string.Format("类型{0}中没有找到{1}属性用于查询条件", entityType.FullName, conditionName));
                    }
                    DbFieldAttribute conditionAttr = DbFieldAttribute.GetCustomAttribute(conditionProperty, typeof(DbFieldAttribute)) as DbFieldAttribute;
                    if (conditionAttr == null)
                    {
                        throw new Exception(string.Format("类型{0}的{1}属性没有标记DbFieldAttribute特性, 无法用于数据库查询",
                                                          entityType.FullName, conditionName));
                    }

                    SqlParameter parameter = GenerateSqlParameter(conditionAttr, conditionProperty.PropertyType, criteria[conditionName]);
                    sqlParameters.Add(parameter);
                    whereBuilder.AppendFormat("[{0}]=@{0} ", conditionAttr.FieldName);
                    whereBuilder.Append("AND ");
                }
            }
            if (whereBuilder.Length > 0)
            {
                whereBuilder.Remove(whereBuilder.Length - 4, 4);
            }

            string sql = BuildPagedSelectSql(selectClause, fromClause, whereBuilder.ToString(), orderBy, pageIndex, pageSize);

            DataSet ds = await connector.ExecuteSqlQuerySet(sql, sqlParameters.ToArray());

            PagedQuery <T> result = new PagedQuery <T>();
            if (ds != null && ds.Tables.Count == 2)
            {
                result.Total           = (int)ds.Tables[0].Rows[0][0];
                ds.Tables[1].TableName = "result";
                result.Records         = await Task.Run(() => ValueHelper.WrapEntities <T>(ds.Tables[1]));
            }
            else
            {
                result.Total   = 0;
                result.Records = new T[0];
            }
            ds.Dispose();
            return(result);
        }