DataReader To List

用了一段时间的Dapper,感觉Dapper比Ado.net好的地方就是转换成实体,到处查资料,写了以下方法,直接可以用。

 using (var conn = new SqlConnection("server=.;database=testdb;uid=testdb;pwd=123456"))
            {
                conn.Open();
                var query = "select * from city";
                var cmd = new SqlCommand(query, conn);
                using (var reader = cmd.ExecuteReader())
                {
                    var citylist = reader.ToList<city>(); //可以取到值,测试OK
                   // reader.Close();
                }
                conn.Close();
            }

 


 

 

    public static class DbDataReaderExtensions
    {
        public static List<T> ToList<T>(this DbDataReader dbdatareader)
        {
            List<T> list = new List<T>();
            List<string> fields = null;
            using (dbdatareader)
            {
                if (fields == null)
                {
                    fields = new List<string>(dbdatareader.FieldCount);
                    for (int i = 0; i < dbdatareader.FieldCount; i++)
                    {
                        fields.Add(dbdatareader.GetName(i).ToLower());
                    }
                }

                while (dbdatareader.Read())
                {
                    T model = Activator.CreateInstance<T>();
                    foreach (PropertyInfo property in model.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
                    {
                        if (fields.Contains(property.Name.ToLower()))
                        {
                            if (!dbdatareader.IsDBNull(dbdatareader.GetOrdinal(property.Name)))
                            {
                                Type convertTo = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
                                property.SetValue(model, Convert.ChangeType(dbdatareader[property.Name], convertTo), null);
                            }
                        }
                    }
                    list.Add(model);
                     
                }
                dbdatareader.Close();
                dbdatareader.Dispose();
            }
            return list;         
        }

}

posted @ 2017-07-18 18:06  China2008  阅读(394)  评论(0编辑  收藏  举报