Methods for assigning values to data table entity classes in. Net

Source: Internet
Author: User
Data

The problem today is how to assign a value to a property in a data entity class. Because a dataset is taken out of the database. If one of the attributes in the data entity class is very clumsy, and we have up to 24 data tables. After searching the web, I wrote a simple method, the code is as follows:

First, let's do a physical class.

1 public class Class1
2 {
3 private int inttemp;
4
5 public int IntTemp
6 {
7 get {return inttemp;}
8 set {inttemp = value;}
9}
10}
11

So how do we find him and assign a value?

The code is as follows:

1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Reflection;
5 using System.Data;
6
7 namespace ConsoleApplication1
8 {
9 Class Program
10 {
One static void Main (string[] args)
12 {
Class1 C = new Class1 ();
14/* Here is the construction of a dataset*/
DataSet ds = new DataSet ();
DataTable dt = new DataTable ();
DT. Columns.Add ("IntTemp", SqlDbType.Int.GetType ());
DataRow dr = dt. NewRow ();
dr["IntTemp"] = 2;
DT. Rows.Add (DR);
DS. Tables.add (DT);
22
23/* Here is the key * *
foreach (DataRow dr1 in DS. Tables[0]. Rows)
25 {
-foreach (DataColumn dc in DR1. Table.columns)
27 {
PropertyInfo pi = C.gettype (). GetProperty (DC. ColumnName)//Get entity class properties created from the table's class name
Pi. SetValue (c, DC. TABLE.ROWS[0][0], NULL);/Set the value of this property
30}
31}
Console.Write (c.inttemp+ "\ n");
33}
34}
35
36}

What's the use of this? When you follow the form of a database table, an entity class can be used to write a common method to assign values to different entity class properties, because Pi. The first value of the SetValue method is in object form. So we have a lot less trouble.

It is not known whether the method is efficient for the majority of the data sets. The masters have looked at me after the change of opinion. Thank you.



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.