2013-07-10 141 views
3

数据库链接泛型列表我有一个类使用反射

public class UserInfo 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public string Address { get; set; } 
} 

,我需要使数据库之间的联系,使用此代码:

using (SqlDataReader reader = cmd.ExecuteReader()) 
{ 
    while (reader.HasRows) 
    { 

    } 
} 

上的所有线路使用反射数据库。

并将它们存储到一个通用的列表:

List<UserInfo> users = new List<UserInfo>(); 

我明白了!

+2

为什么不使用[许多可用的ORM]之一(http://en.wikipedia.org/wiki/List_of_object-relational_mapping_software#.NET)而不是滚动自己的? – GolfWolf

+0

这是你的意思吗? http://stackoverflow.com/questions/12662318/how-to-convert-datatable-to-listt-using-reflections – Winks

+0

我明白了!谢谢 ! – SanRyu

回答

1

我知道了!!

这是结果,也许有人需要它!

public List<UserInfo> GetAllUsers() 
{ 
    List<UserInfo> users = new List<UserInfo>(); 

    try 
    { 
     using (SqlConnection sqlConnection = connectionString) 
     { 
      using (SqlCommand cmd = new SqlCommand()) 
      { 
       cmd.CommandText = "dbo.GetAllUsers"; 
       cmd.CommandType = CommandType.StoredProcedure; 

       cmd.Connection = sqlConnection; 
       sqlConnection.Open(); 

       using (SqlDataReader dataReader = cmd.ExecuteReader()) 
       { 
        if (dataReader.HasRows) 
        { 
         while (dataReader.Read()) 
         { 
          UserInfo user = new UserInfo(); 
          PropertyInfo[] pList = typeof(UserInfo).GetProperties(); 
          foreach (PropertyInfo pi in pList) 
          { 
           object value = dataReader[pi.Name]; 
           if (!value.GetType().Equals(typeof(DBNull))) 
           { 
            users.GetType().GetProperty(pi.Name, BindingFlags.Public | BindingFlags.Instance).SetValue(user, value, null); 
           } 
          } 
          users.Add(user); 
         } 
        } 
        else 
        { 
         users = null; 
        } 
       } 
      } 
      sqlConnection.Close(); 
     } 
    } 


    catch (Exception) 
    { 
     return null; 
    } 

    return users; 
}