使用泛型查询数据小例
时间:2011-05-09 来源:Mike Corleone
在这个例子当中,泛型的出色之处在于,不必为每个类型编写相同的代码讲阅读器的数据转换为泛型List。
1.GenericMethods类
public class GenericMethods
{
public static List<T> GetListFromCommand<T>(SqlCommand command)
where T : ICreatable, new()
{
List<T> list = new List<T>();
using (command.Connection)
{
command.Connection.Open();
SqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
T t = new T();
t.Create(dr);
list.Add(t);
}
}
return list;
}
}
2.Movie实体类
public class Movie : ICreatable
{
public int ID { get; set; }
public string Name { get; set; }
public void Create(SqlDataReader dr)
{
ID = int.Parse(dr["ID"].ToString());
Name = dr["Name"].ToString();
}
}
3.ICreatable接口
public interface ICreatable
{
void Create(SqlDataReader dr);
}
4.页面方法调用
string constring = WebConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
SqlCommand command = new SqlCommand("SELECT * FROM Movies", conn);
List<Movie> list = GenericMethods.GetListFromCommand<Movie>(command);
相关阅读 更多 +