In the past, when I wrote PHP to query all the arrays, it was also very easy to perform loop operations. Suddenly, I was a little unaccustomed to using. NET and did not know how to operate it.
Now, the data content is converted into corresponding entity classes using generics and reflection.
I heard that the efficiency is very low. I don't want to worry about it. You can use it.
public class Mapping {
public static T Entity<T>(IDataReader reader,Dictionary<string,int> dictionary) {
var type = typeof(T);
//T u = new T();
T u = Activator.CreateInstance<T>();
PropertyInfo[] field = type.GetProperties();
int index = -1;
foreach (var f in field) {
if (dictionary.TryGetValue(f.Name, out index)) {
var r = reader.GetValue(index);
if(r != DBNull.Value)
f.SetValue(u, r, null);
}
}
return u;
}
}
The first parameter does not need to be explained, and the second parameter I post out the code.
Dictionary<string, int> dictionary = new Dictionary<string, int>();
var dr = cmd.ExecuteReader();
int count = dr.FieldCount;
for (int i = 0; i < count; i++) {
dictionary.Add(dr.GetName(i), i);
}
In this case, the corresponding attribute name and its corresponding key are obtained from the dictionary during the following reflection.
The following is the complete code for querying and converting it into an object class.
public List<T> findAll<T>() {
var list = new List<T>();
//var parame = new List<QueryParameter>();
//parame.Add("uid");
Dictionary<string, int> dictionary = new Dictionary<string, int>();
using (SqlConnection conn = new SqlConnection(sqlConnectionString)) {
String sql = "SELECT uid,username FROM Users ORDER BY uid DESC";
SqlCommand cmd = new SqlCommand(sql, conn);
//SqlParameter p = new SqlParameter("@uid", 1);
//cmd.Parameters.Add(p);
conn.Open();
var dr = cmd.ExecuteReader();
int count = dr.FieldCount;
for (int i = 0; i < count; i++) {
dictionary.Add(dr.GetName(i), i);
}
while (dr.Read()) {
list.Add(Mapping.Entity<T>(dr,dictionary));
}
dr.Close();
conn.Close();
}
return list;
}