如何将Sqldatareader返回到列表< Class> [英] How Can I Return Sqldatareader Into List<Class>
本文介绍了如何将Sqldatareader返回到列表< Class>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何返回List< student> by ado .net 2.0
How can i return List<student> by ado .net 2.0
public class Student
{
public int _rollnumber{get;set;}
public string _name{get;set;}
public string _address{get;set;}
}
我的功能是,
My function is,
public List<Student> GetAllTableData()
{
conStr = ConfigurationManager.ConnectionStrings["SqlConnection"].ToString();
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("select * from Students", con);
//what to write after this
SqlDataReader dr=cmd.ExecuteReader();
}
推荐答案
您应该使用阅读器来读取SQL命令的所有结果,例如下一个例子:
You should use the reader to read all results of your SQL command, like in the next example:
List<Student> resultList= new List<Student>();
while (reader.Read())
{
Student entity= new Student();
entity.ID = (int)reader["ID"];
entity.Name= (string)reader["Name"];
// ...
//
resultList.Add(entity);
}
return resultList;
List<student> list = new List<student>();
while (dr.Read())
{
Student student = new Student();
student._rollnumber = (int) dr["RollNumber"];
student._name = (string) dr["StudentName"];
student._address = (string) dr["Address"];
list.Add(student);
}</student></student>
但是,请遵循正确的命名约定!
属性 不 以下划线开头:它们以大写字母。下划线用于为后备存储变量添加前缀,以将它们与它们关联的属性区分开来:
But please, follow proper naming conventions!
Properties should not start with an underline: they start with an Upper case letter. Underscores are used to prefix backing store variables to differentiate them from the property they are associated with:
public class Student
{
public int Rollnumber{get;set;}
public string Name{get;set;}
private string _Address;
public string Address
{
get { return _Address; }
set { _Address = value; }
}
}
我使用了 AutoMapper [ ^ ]一次......
I used the AutoMapper[^] for that once...
这篇关于如何将Sqldatareader返回到列表< Class>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文