以下是根据我个人自己的理解然后实现的,如果能有更好的实现方式希望各位能指点一二
查询方法
public static IEnumerable<T> Query<T>(this IDbConnection conn, string sql, params SqlParameter[] parameters)
{
using (conn)
{
List<T> dataList = new List<T>();
Type t = typeof(T);
SqlCommand comm = conn.CreateCommand() as SqlCommand;
comm.CommandText = sql;
comm.Parameters.AddRange(parameters);
conn.Open();
SqlDataReader reader = comm.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
dataList.Add((T)GetClassProperty(reader, t));
}
reader.Close();
return dataList;
}
}
public static IEnumerable<T> Query<T>(this IDbConnection conn) where T : class
{
using (conn)
{
List<T> dataList = new List<T>();
Type t = typeof(T);
PropertyInfo[] propertyInfo = t.GetProperties();
SqlCommand comm = conn.CreateCommand() as SqlCommand;
string tableName = GetDataTableNameByAttr(t);
StringBuilder cloumnStr = new StringBuilder();
foreach (PropertyInfo property in propertyInfo)
{
if (property.PropertyType.IsConstructedGenericType || (!property.PropertyType.IsPrimitive && !property.PropertyType.Equals(typeof(string)) && property.PropertyType.IsClass)) continue;
cloumnStr.Append(property.Name + ",");
}
comm.CommandText = string.Format("SELECT {0} FROM {1}", cloumnStr.ToString().TrimEnd(','), tableName);
conn.Open();
SqlDataReader reader = comm.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
dataList.Add((T)GetClassProperty(reader, t));
}
reader.Close();
return data