In general, we use ADO. NET to query the database and return the generic set; and use SqlDataReader to read data and store the data to the object row by row.
Code
/// <Summary>
/// Obtain the UserInfo generic set
/// </Summary>
/// <Param name = "connStr"> database connection string </param>
/// <Param name = "sqlStr"> T-SQL to query </param>
/// <Returns> </returns>
Public IList <UserInfo> GetUserInfoAll (string connStr, string sqlStr)
{
Using (SqlConnection conn = new SqlConnection (connStr ))
{
Using (SqlCommand cmd = new SqlCommand (sqlStr, conn ))
{
SqlDataReader sdr = cmd. ExecuteReader ();
IList <UserInfo> list = new List <UserInfo> ();
While (sdr. Read ())
{
UserInfo userInfo = new UserInfo ();
UserInfo. ID = (Guid) sdr ["ID"];
UserInfo. LoginName = sdr ["LoginName"]. ToString ();
UserInfo. LoginPwd = sdr ["LoginPwd"]. ToString ();
List. Add (userInfo );
}
Return list;
}
}
}
Although the required data is returned in this way, it is very troublesome to create such a method for each table when there are many database tables. This also increases the repetitive labor force.
However, it is inconvenient to directly return data sets. DataSet is a weak type. It is not as efficient as generic set operations!
At this time, we need to extract a general conversion method called DataSetToList.
Code
1 /// <summary>
2 // obtain the generic set
3 /// </summary>
4 /// <typeparam name = "T"> type </typeparam>
5 // <param name = "connStr"> database connection string