我一直致力于使用Datareader从SQL数据库中检索数据并将其填充到Datatable中。但是,我想知道是否有办法处理来自datareader 的数据而不使用数据表? I mean-使用对象处理表值应该更优选..
但是,我不想在这里使用LINQ,因为我将使用ADOMD对象从数据库中提取数据(Cubes)..
答案 0 :(得分:1)
看看dapper-dot-net。我不确定它如何与ADOMD.NET一起工作,但它确实在动态对象中巧妙地实现了查询结果。
答案 1 :(得分:1)
只需循环遍历项目并将其设置为自定义类的属性值。以下示例从Customer表读取数据并创建Customer Class对象列表。假设您有一个客户POCO,其ID和名称为属性
List<Customer> custList= new List<Customer>();
string connString="yourConnectionStringHere";
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT ID,NAME From Customer";
using (var reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
var cust= new Customer();
if (!reader.IsDBNull( reader.GetOrdinal("ID")))
cust.ID = reader.GetInt32(reader.GetOrdinal("ID"));
if (!reader.IsDBNull( reader.GetOrdinal("Name")))
cust.Name = reader.GetString(reader.GetOrdinal("Name"));
custList.Add(cust);
}
}
}
}
}
答案 2 :(得分:0)
public List GetEmployee(string spname) {
con.Open();
cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = spname;
cmd.CommandType = CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
List<EmployeeDetails> lstemp = new List<EmployeeDetails>();
while (reader.Read())
{
EmployeeDetails emp = new EmployeeDetails();
emp.EmployeeId =Convert.ToInt32( reader["EmployeeId"].ToString());
emp.FirstName = reader["FirstName"].ToString();
emp.LastName = reader["LastName"].ToString();
emp.DOB = Convert.ToDateTime(reader["DOB"].ToString());
emp.Gender = Convert.ToInt32(reader["Gender"].ToString());
emp.QName = reader["QName"].ToString();
emp.Dname = reader["DName"].ToString();
emp.Email = reader["Email"].ToString();
lstemp.Add(emp);
}
return lstemp;
}