In C #, object attributes and database fields are reflected and assigned values.

Source: Internet
Author: User

In actual development, we often need to read data from the database and assign values to the corresponding attributes of the object class. There are a lot of such code in. Text DataDTOProvider, such:

Public Role [] GetRoles (IDataReader reader) {System. collections. arrayList al = new System. collections. arrayList (); try {while (reader. read () {Role role = new Role (); if (reader ["RoleID"]! = DBNull. Value) {role. RoleID = (int) reader ["RoleID"];} if (reader ["Names"]! = DBNull. Value) {role. Names = (string) reader ["Names"];} if (reader ["Description"]! = DBNull. value) {role. description = (string) reader ["Description"];} al. add (role) ;}} finally {reader. close ();} return (Role []) al. toArray (typeof (Role ));}
 

I think the above Code is not elegant:
1. Each time you assign a value to the Role attribute, check whether the reader value is DBNull.
2. Each time a Role attribute is assigned a value, type conversion is required. The type of the Role attribute is known. Can this conversion be automatically completed?
3. Each time a Role attribute is assigned a value, the Role attribute corresponds to the database field. If we ensure that the same name is used for the database field and the object class attribute when designing the database and object class, we can use reflection to automatically map the attributes and fields through code. Even if the database field and attribute are different, we can change the query statement to achieve this.
Can I improve the code above to make the code more elegant? What kind of elegant code should be like? If we use ReaderToObject (reader, role); instead of the previous statement that assigns values to the Role attribute, will it make the code more elegant? ReaderToObject is used to automatically write the values in reader to the corresponding attributes in role (provided that the fields in reader have the same name as the attributes in role ). Now our task is to implement ReaderToObject. With the powerful weapon-Reflection, our task becomes very easy and I will not talk about it anymore. The following code is my implementation method:

Private void ReaderToObject (IDataReader reader, object targetObj) {for (int I = 0; I <reader. fieldCount; I ++) {System. reflection. propertyInfo propertyInfo = targetObj. getType (). getProperty (reader. getName (I); if (propertyInfo! = Null) {if (reader. GetValue (I )! = DBNull. value) {if (propertyInfo. propertyType. isEnum) {propertyInfo. setValue (targetObj, Enum. toObject (propertyInfo. propertyType, reader. getValue (I), null);} else {propertyInfo. setValue (targetObj, reader. getValue (I), null );}}}}}
 

ReaderToObject can read data from reader into any entity class. The ing principle between database fields and object attributes is the same name. Of course, we can also map the two through the configuration file.
All code is as follows:

Private void button2_Click (object sender, EventArgs e) {Role [] role; SqlConnection con = new SqlConnection ("Data Source = SLY \ SQLEXPRESS; Initial Catalog = ManagerRoles; user ID = sa "); SqlCommand cmd = new SqlCommand (" select * from Roles ", con); SqlDataReader dr; con. open (); dr = cmd. executeReader (); DataDAL dataDal = new DataDAL (); role = dataDal. getRoles (dr); con. close (); textBox2.Text = role [0]. roleID. ToString (); textBox3.Text = role [0]. names. toString (); textBox4.Text = role [0]. description. toString ();} class: DataDAL public Role [] GetRoles (IDataReader reader) {System. collections. arrayList al = new System. collections. arrayList (); try {while (reader. read () {Role role = new Role (); ReaderToObject (reader, role); al. add (role) ;}} finally {reader. close ();} return (Role []) al. toArray (typeof (Role ));} Private void ReaderToObject (IDataReader reader, object targetObj) {for (int I = 0; I <reader. fieldCount; I ++) {System. reflection. propertyInfo propertyInfo = targetObj. getType (). getProperty (reader. getName (I); if (propertyInfo! = Null) {if (reader. GetValue (I )! = DBNull. value) {if (propertyInfo. propertyType. isEnum) {propertyInfo. setValue (targetObj, Enum. toObject (propertyInfo. propertyType, reader. getValue (I), null);} else {propertyInfo. setValue (targetObj, reader. getValue (I), null) ;}}} entity class: Role int roleID; public int RoleID {get {return roleID;} set {roleID = value ;}} string names; public string Names {get {return names;} set {names = value ;}} string description; public string Description {get {return description ;} set {description = value ;}}
 

 

The original author does not know who it is, but this code is still uncomfortable to use, so I wrote it myself...

If you have any questions, please criticize and correct them.

 

Public List <Object> SelectClassFS (Object tableClass)
{
String className = tableClass. ToString (). Substring (tableClass. ToString (). IndexOf ('.') + 1 );
String tableName = className. Substring (0, className. LastIndexOf ('D '));
MethodInfo [] miClass;
// Object milist = (Object) Activator. CreateInstance (tableClass. GetType ());
List <Object> reList = new List <Object> ();

OracleCommand Ocmd = new OracleCommand ("select * from" + tableName );
Ocmd. Connection = Oconn;
OracleDataReader odr = Ocmd. ExecuteReader ();

While (odr. Read ())
{

Type tp = tableClass. GetType ();
MiClass = tp. GetMethods ();
Object mis = (Object) Activator. CreateInstance (tableClass. GetType ());
Foreach (MethodInfo _ mi in miClass)
{

String memberName = _ mi. Name. Substring (_ mi. Name. IndexOf ('_') + 1 );
If (_ mi. Name! = "Set _" + memberName) continue;
// MethodInfo _ mi = tp. GetMethod (_ mi. Name );
_ Mi. Invoke (mis, new object [] {odr [memberName]. ToString ()});

}
ReList. Add (mis );
}
Ocmd. Clone ();
Return reList;
}

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.