When using. NET development, it is very convenient for you to return the query results as a datatable, but it is very troublesome to retrieve data and there is no convenient model type retrieval.
Therefore, many people do this in the following ways:
// Obtain the query result
Datatable dt = dbhelper. executedatatable (...);
// Convert datatable to ilist <userinfo>
Ilist <userinfo> Users = converttouserinfo (DT );
Q: If the system has dozens or even hundreds of models, isn't every model having to write a method to convert datatable to this model?
Solution: Can I write a common class and convert the able to any model? Well, reflection and generics are needed.
The following is the core code. It has been tested and has good performance. You can improve it based on your actual situation.
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. Data;
Using system. reflection;
Namespace flexzoo. Data
{
/// <Summary>
/// Entity conversion helper class
/// </Summary>
Public class modelconverthelper <t> where T: New ()
{
Public static ilist <t> converttomodel (datatable DT)
{
// Define a set
Ilist <t> TS = new list <t> ();
// Obtain the model type
Type type = typeof (t );
String tempname = "";
Foreach (datarow DR in DT. Rows)
{
T = new T ();
// Obtain the public attributes of this model
Propertyinfo [] propertys = T. GetType (). getproperties ();
Foreach (propertyinfo PI in propertys)
{
Tempname = pi. Name;
// Check whether the datatable contains this column
If (Dt. Columns. Contains (tempname ))
{
// Determine whether the property has a setter
If (! Pi. canwrite) continue;
Object value = Dr [tempname];
If (value! = Dbnull. value)
Pi. setvalue (T, value, null );
}
}
TS. Add (t );
}
Return ts;
}
}
}
Usage:
// Obtain the query result
Datatable dt = dbhelper. executedatatable (...);
// Convert datatable to ilist <userinfo>
Ilist <userinfo> Users = modelconverthelper <userinfo>. converttomodel (DT );