Go C # Reflection, binding database query data and entity classes based on reflection, no entity class assignment

Source: Internet
Author: User
Tags reflection

This article from: http://www.cnblogs.com/mrchenzh/archive/2010/05/31/1747937.html

/*****************************************
* Description: Use reflection to automatically bind the contents of a database query
* To entity class
*
* Time: 1:49 2009-9-19
*
* Programmer: Wang Wenjung
* ***************************************/
/**************** Database Script ***************
* CREATE DATABASE MySchool
* Go
* Use MySchool
* Go
* CREATE TABLE Student
* (
* ID int Identity primary KEY,
* Name varchar (10)
* )
* ****************************************/
Using System;
Using System.Reflection;
Using System.Data.SqlClient;
Using System.Data;
Using System.Collections.Generic;

Namespace Reflectiondemo
{
#region Main
Class Program
{
static void Main (string[] args)
{
DataSet ds = new DataSet ();

Building a DataSet #region connection database

SqlConnection con = new SqlConnection ("Data source=.;i Nitial catalog=myschool;integrated security=true ");
SqlDataAdapter objadapter = new SqlDataAdapter ("SELECT * from student", con);
Objadapter.fill (DS);

#endregion

#region Build a DataSet manually

DataTable dt = new DataTable ();
Dt. Columns.Add ("ID");
Dt. Columns.Add ("Name");
DataRow row = dt. NewRow ();
row["ID"] = 1;
row["Name"] = "grey too Wolf";
Dt. Rows.Add (row);
Ds. Tables.add (DT);
#endregion

list<student> students = new list<student> ();
foreach (DataRow DataRow in DS. Tables[0]. Rows)
{
Student stu = new Student ();
Utility.converttoentity (Stu, Row);
Students. ADD (Stu);
}
foreach (Student Student in students)
{
Console.WriteLine (student. Name);
}
}
}
#endregion

#region Entity Classes

<summary>
Entity class that needs to be in the property
Add custom attributes on
Each entity class corresponds to the data table
A field, note that the parameters in the custom attribute
Be sure to correspond to field one by one in the data table,
Otherwise it will not be reflected!
</summary>
public class Student
{
[Datacontextattribute ("ID")]
public int ID {get; set;}
[DataContext ("Name")]
public string Name {get; set;}
}

#endregion

#region Custom Attributes

<summary>
Custom Attributes
</summary>
[AttributeUsage (Attributetargets.property)]
public class Datacontextattribute:attribute
{
<summary>
Custom Attributes
</summary>
<param name= "FieldName" > Data table field name </param>
Public Datacontextattribute (string property) {this. Property = property; }
<summary>
Data table field properties (Entity properties)
</summary>
public string Property {get; set;}
}

#endregion

#region Reflection

public class Utility
{
<summary>
Convert a DataRow into an entity
</summary>
<param name= "obj" > Entities </param>
<param name= "Row" > Data table row Data </param>
public static void Converttoentity (Object obj, DataRow row)
{
Get the type of obj
Type type = obj. GetType ();
Returns all public properties of this type
propertyinfo[] Infos = type. GetProperties ();
Looping Public Property arrays
foreach (PropertyInfo info in infos)
{
Returns an array of custom attributes
object[] Attributes = info. GetCustomAttributes (typeof (Datacontextattribute), false);
Looping a custom property array
foreach (Datacontextattribute attribute in attributes)
{
If this column is included in the DataRow
if (row. Table.Columns.Contains (attribute. property))
{
Assigns the value of the DataRow specified column
Object value = Row[attribute. Property];
Returns if value is null
if (value = = DBNull.Value) continue;
Convert a value
if (info. Propertytype.equals (typeof (String)))
{
Value = Row[attribute. Property]. ToString ();
}
else if (info. Propertytype.equals (typeof (int)))
{
Value = Convert.ToInt32 (Row[attribute. Property]);
}
else if (info. Propertytype.equals (typeof (decimal)))
{
Value = Convert.todecimal (Row[attribute. Property]);
}
else if (info. Propertytype.equals (typeof (DateTime)))
{
Value = Convert.todatetime (Row[attribute. Property]);
}
else if (info. Propertytype.equals (typeof (Double)))
{
Value = Convert.todouble (Row[attribute. Property]);
}
else if (info. Propertytype.equals (typeof (BOOL)))
{
Value = Convert.toboolean (Row[attribute. Property]);
}
Use reflection to automatically assign value to the corresponding public property of obj
Info. SetValue (obj, value, null);
}
}
}
}
}

#endregion
}

Go C # Reflection, binding database query data and entity classes based on reflection, no entity class assignment

Related Article

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.