ASP. NET: static method for filling the List of generic sets through reflection

Source: Internet
Author: User
Static Methods for filling data from DataReader to a data entity generic set through reflection.

// Kchen. Core. BaseBusinessObject is a common data entity class. here only the types inherited by T are limited.
Public static IList <T> FillDataListGeneric <T> (System. Data. IDataReader reader) where T: Kchen. Core. BaseBusinessObject
{
// Instantiate a List <> generic set
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 T type.
T RowInstance = Activator. CreateInstance <T> ();
// Obtain all the properties of the object through reflection
Foreach (PropertyInfo Property in typeof (T). GetProperties ())
{
// Bindingfieldattriattribute is a custom Attribute used for binding to database fields.
Foreach (BindingFieldAttribute FieldAttr in Property. GetCustomAttributes (typeof (bindingfieldattrites), true ))
{
Try
{
// Obtain the order of fields in the current database
Int Ordinal = reader. GetOrdinal (FieldAttr. FieldName );
If (reader. GetValue (Ordinal )! = DBNull. Value)
{
// Fill the data read by DataReader into the attributes of the object.
Property. SetValue (RowInstance, Convert. ChangeType (reader. GetValue (Ordinal), Property. PropertyType), null );
}
}
Catch
{
Break;
}
}
}
// Add the data entity object to the generic set
DataList. Add (RowInstance );
}
Return DataList;
}
Use the following code when calling

// Pseudocode OleDbDataReader _ ds = create an OleDbDataReader
IList <Product >_result = Kchen. Utilities. FillDataListGeneric <Product> (_ ds );

This static method uses an object type and a DateReader to quickly fill data in a data object generic set.

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.