Set | static
Well, it took a whole night, and it finally got out. How to populate a static method of data entity generic collections from DataReader by reflection.
Kchen.Core.BaseBusinessObject is a generic data entity class, where only the types inherited by T are qualified
public static ilist<t> filldatalistgeneric<t> (System.Data.IDataReader reader) where T: Kchen.Core.BaseBusinessObject
{
Instantiating a list<> generic collection
ilist<t> DataList = new list<t> ();
while (reader. Read ())
{
Because it is an unknown type, you must use the Activator.createinstance<t> () method to dynamically create a data entity object based on the type of T
T rowinstance = activator.createinstance<t> ();
Get all property of object by reflection
foreach (PropertyInfo property in typeof (T). GetProperties ())
{
Bindingfieldattribute is a custom attribute used to bind to a database field
foreach (Bindingfieldattribute fieldattr in Property.getcustomattributes (typeof (Bindingfieldattribute), true)
{
Try
{
Get the order of the current database fields
int Ordinal = reader. GetOrdinal (Fieldattr.fieldname);
if (reader. GetValue (Ordinal)!= DBNull.Value)
{
To populate the properties of an object entity with data read from DataReader
Property.setvalue (Rowinstance, Convert.changetype (reader). GetValue (Ordinal), property.propertytype), NULL);
}
}
Catch
{
Break
}
}
}
Add a data entity object to a generic collection
Datalist.add (rowinstance);
}
return DataList;
}
Use the following code when calling
Pseudo-code OleDbDataReader _ds = Create a OleDbDataReader
ilist<product> _result = kchen.utilities.filldatalistgeneric<product> (_ds);
This static method quickly populates the data entity generic collection with an entity type and datereader.