C # able to ilist

Source: Internet
Author: User

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 );

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.