事件调用List<T>QueryByADO<T>方法
private void button2_Click(object sender, EventArgs e)
{
string sqlText = " select* from dbo.SendSMS where id % 5 = 1 and sms_type = '0'";
string connStr = "Server=(local);database=BjhszhSendSMS;integrated security=SSPI";
QueryByADO<T>(connStr, sqlText);//调用List<T>QueryByADO<T>方法
}
链接数据,获取数据并将数据传给ConvertToModel<T>(dt);
public List<T> QueryByADO<T>(string connStr, string sql) where T : class, new()
{
try
{
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
SqlDataAdapter myda = new SqlDataAdapter(sql, conn);
DataTable dt = new DataTable();
myda.Fill(dt);
return ConvertToModel<T>(dt);
}
catch (Exception ex)
{
throw ex;
}
}
将DataTable数据源转换成实体类
public List<T> ConvertToModel<T>(DataTable dt) where T : class, new()
{
List<T> ts = new List<T>();// 定义集合
foreach (DataRow dr in dt.Rows)
{
T t = new T();
PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
foreach (PropertyInfo pi in propertys)
{
if (dt.Columns.Contains(pi.Name))
{
if (!pi.CanWrite) continue;
var value = dr[pi.Name];
if (value != DBNull.Value)
{
if (!pi.PropertyType.IsGenericType)
{
//非泛型
pi.SetValue(t, value == null ? null : Convert.ChangeType(value, pi.PropertyType), null);
}
else
{
//泛型Nullable<>
Type genericTypeDefinition = pi.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
pi.SetValue(t, value == null ? null : Convert.ChangeType(value, Nullable.GetUnderlyingType(pi.PropertyType)), null);
}
}
}
}
}
ts.Add(t);
}
return ts;
}
}
一定要写class类T实体对象,如果有数据库实体类,请忽略,
internal class T
{
public string sms_name { get; set; }
public string sms_phone { get; set; }
public string sms_type { get; set; }
}