Static methods for populating a generic collection list by reflection

Source: Internet
Author: User
Tags foreach reflection
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.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.