c# 数据库类型转实体

public static class DbHelper
    {
        public static List<T> GetData<T>(string sql)
        {
            var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["xxx"].ToString());
            connection.Open();
            SqlCommand command = connection.CreateCommand();
            command.CommandText = sql;
            command.CommandType = CommandType.Text;
            var reader = command.ExecuteReader();
            var list = GetList<T>(reader);
            command.Connection.Close();
            return list;
        }
        private static List<T> GetList<T>(SqlDataReader reader)
        {
            var list = new List<T>();
            while (reader.Read())
            {
                list.Add(Get<T>(reader));
            }
            reader.Close();
            reader.Dispose();
            return list;
        }
        private static T Get<T>(SqlDataReader reader)
        {
            var t = Activator.CreateInstance<T>();
            var type = typeof(T);
            foreach (var field in type.GetProperties())
            {
                var value = reader[field.Name] is DBNull ? null : reader[field.Name];
                field.SetValue(t, value);
            }
            return t;
        } 
    }

你可能感兴趣的:(c# 数据库类型转实体)