Example #1
0
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <typeparam name="T">返回实体class</typeparam>
        /// <param name="db">IDatabase</param>
        /// <param name="sql">sql 语句,参数用@前缀,自动识别数据库类型</param>
        /// <param name="obj">参数:class or Dictionary&lt;string, object&gt;,class属性 or key必须与参数名称一致</param>
        /// <returns>实体 list</returns>
        public static List <T> Query <T>(this IDatabase db, string sql, object obj = null)
        {
            var list = new List <T>();
            var t    = typeof(T);

            if (t.IsArray || t.IsAbstract)
            {
                return(list);
            }

            IReaderToModel ic      = null;
            bool           isvalue = false;

            if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                var gt = t.GetGenericArguments()[0];
                if (gt.IsPrimitive && gt.IsValueType)
                {
                    isvalue = true;
                }
            }

            if (!isvalue && (t == typeof(string) || t.IsPrimitive && t.IsValueType))
            {
                isvalue = true;
            }
            if (!isvalue && t.IsClass)
            {
                ic = GetReaderToModel(t);
            }

            db.ClearParameters();
            AddParam(db, sql, obj);
            using (var reader = db.ExecuteReader())
            {
                while (reader.Read())
                {
                    object o = default(T);
                    if (isvalue)
                    {
                        var v = reader.GetValue(0);
                        o = ChangeType(v, t) ?? default(T);
                    }
                    else if (ic != null)
                    {
                        o = ic.To(reader);
                    }
                    list.Add((T)o);
                }
            }

            return(list);
        }
Example #2
0
        private static IReaderToModel GetReaderToModel(Type t)
        {
            IReaderToModel ic          = null;
            Type           convertType = null;

            if (!cacheDic.TryGetValue(t, out convertType))
            {
                if (convertType == null)
                {
                    convertType = CreateReaderToModelType(t);
                    if (convertType != null && !cacheDic.ContainsKey(t))
                    {
                        cacheDic[t] = convertType;
                    }
                }
            }

            if (convertType != null)
            {
                ic = Activator.CreateInstance(convertType) as IReaderToModel;
            }

            return(ic);
        }