Ejemplo n.º 1
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);
            }
        }