使用泛型集合简化数据查询

使用三层开发的时候发现dal层读取数据有很多垃圾内容,所以想到用泛型集合简化数据查询

第一步:创建接口ICreateable

/// <summary>
///ICreatable 的摘要说明
/// </summary>
public interface ICreatable
{
    
void Create(SqlDataReader reader);
    
}

 

第二步:在一个类adminService.cs,在里面添加方法GetListFromComand

 

代码
  //接收一个SqlCommand对象并且返回一个泛型List<T>.where子句用来约束方形类型,泛型约束使得类型T必须实现ICreate接口并且可以通过new实例化
    public static List<T> getListFromCommand<T>(SqlCommand command) where T : ICreatable, new()
    {
        List
<T> results = new List<T>();
        
using (command.Connection)
        {
            command.Connection.Open();
            SqlDataReader reader 
= command.ExecuteReader();
            
while (reader.Read())
            {
                T newThing 
= new T();
                newThing.Create(reader);
                results.Add(newThing);
            }
        }
        
return results;
    }

 

第三步:实体类实现接口ICreateable

 

代码
/// <summary>
///admin 的摘要说明
/// </summary>
public class admin : ICreatable
{
    
    
public admin()
    {
        
//
        
//TODO: 在此处添加构造函数逻辑
        
//
    }
    
//自动属性
    public int id { getset; }
    
public string password { getset; }

    
#region ICreatable 成员

    
public void Create(SqlDataReader reader)
    {
        id 
= Convert.ToInt32(reader["id"]);
        password 
= (string)reader["password"];
    }

    
#endregion


}

 

第四步:页面.cs中使用泛型集合显示数据

 

代码
  protected void Page_Load(object sender, EventArgs e)
    {
        LinQBind();
        
//intial();
    }
    
    
public void LinQBind()
    {
        
string conString = "Data Source=.;Initial Catalog=DataBase;User ID=sa;password=123";
        SqlConnection con 
= new SqlConnection(conString);
        
        SqlCommand cmd 
= new SqlCommand("select * from admin", con);
        List
<admin> listAdmin = adminService.getListFromCommand<admin>(cmd);
    
        GridView1.DataSource 
= listAdmin;
        GridView1.DataBind();
       

    }

 

 

posted @ 2010-05-26 16:30  蜉蝣  阅读(326)  评论(0)    收藏  举报