利用泛型、反射 读取数据库数据

来源:互联网 发布:外国人吃中国食物 知乎 编辑:程序博客网 时间:2024/05/16 02:05

//基类

public abstract class BaseDAL
{
 public BaseDAL()
 {
  //
  //TODO: 在此处添加构造函数逻辑
  //
 }
     protected List<T> GetTabList<T>(SqlDataReader reader)
            where T : class,new()
        {
             List<T> list = new List<T>();
           try
            {
               while (reader.Read())
           {
               T entity = new T();
               for (int i = 0; i < reader.FieldCount; i++)
               {
                   PropertyInfo proinfo = entity.GetType().GetProperty(reader.GetName(i));
                   proinfo.SetValue(entity, reader.GetValue(i), null);//这里最好判断一下reader.GetValue(i)的数据类型,以及在数据库中是否为DbNULL
               }
               list.Add(entity);
           }
           }
           catch (Exception ex)
           {
              
               throw ex;
           }
                  
           return list;
       }
}

 

//子类

public class CompanyDAL:BaseDAL
{
   
 public CompanyDAL()
 {
  //
  //TODO: 在此处添加构造函数逻辑
  //
 }
    public List<Company> GetAllCompany()
    {
        List<Company> list = new List<Company>();
        using (SqlConnection conn = new SqlConnection("data source=.;database=DBTest;uid=sa;pwd=sa;"))
        {
            conn.Open();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.CommandText = "select * from T_Company";

            SqlDataReader sdr = cmd.ExecuteReader();

            list = base.GetTabList<Company>(sdr);
            conn.Close();
        }
        return list;
    }
}

//实体类
public class Company
{
    private int id;

    public int Id
    {
        get { return id; }
        set { id = value; }
    }
    private string cName;

    public string CName
    {
        get { return cName; }
        set { cName = value; }
    }
}

 

 

//Web

List<Company> list = (new CompanyDAL()).GetAllCompany();
        this.GridView1.DataSource = list;
        this.GridView1.DataBind();

原创粉丝点击