Write a MyORM -- Using Reflection, myorm -- Using Reflection

Source: Internet
Author: User

Write a MyORM -- Using Reflection, myorm -- Using Reflection

This article aims to better understand reflection.

ORM: Object Relational Mapping Object ing solves the problem of mismatch between object-oriented languages and Relational databases.

ORM is an idea. There are many technologies that implement this idea, such as Entity Framework in C #, NHibernate, and Hibernate in Java.

 

Create a console application and add a class, Person. cs

1 public class Person2     {3        public int Id { get; set; }4        public string Name { get; set; }5        public int Age { get; set; }6     }

Add a class, MyORM. cs

1 public class MyORM 2 {3 private static readonly string connstr = ConfigurationManager. connectionStrings ["connstr"]. connectionString; 4 // hypothesis: table name and class name are consistent 5 /// <summary> 6 /// insert a data record 7 /// </summary> 8 /// <param name = "obj"> insert </param> 9 // <returns> affected function </returns> 10 public int Insert (object obj) 11 {12 Type type = obj. getType (); 13 string className = type. name; // person14 // insert into Person (Name, Ag E) values ("Haha", 10) 15 PropertyInfo [] props = type. getProperties (); 16 List <string> propNames = new List <string> (); // attribute name List 17 List <string> paraNames = new List <string> (); // List of parameter names 18 List <MySqlParameter> paramters = new List <MySqlParameter> (); // parameter 19 foreach (PropertyInfo prop in props) 20 {21 string propName = prop. name; 22 if (propName! = "Id") 23 {24 propNames. add (propName); 25 paraNames. add ("@" + propName); 26 MySqlParameter para = new MySqlParameter (propName, prop. getValue (obj); 27 paramters. add (para); 28} 29} 30 StringBuilder sqlsb = new StringBuilder (); 31 sqlsb. append ("insert "). append (className ). append ("("). append (string. join (",", propNames )). append (") values ("). append (string. join (",", paraNames )). append (")"); 32 return MySqlHelper. executeNonQuery (connstr, sqlsb. toString (), paramters. toArray (); 33} 34 // query 35 public object SelectById (Type type, int Id) 36 {37 object obj = Activator by id. createInstance (type); 38 // select * from Person where Id = 139 string className = type. name; 40 string SQL = "select * from" + className + "where Id = @ Id"; 41 MySqlParameter para = new MySqlParameter ("@ Id", id ); 42 DataSet ds = MySqlHelper. executeDataset (connstr, SQL, para); 43 DataTable table = ds. tables [0]; 44 if (table. rows. count <= 0) 45 {46 return null; // No data found 47} 48 else if (table. rows. count> 1) 49 {50 throw new Exception ("A big problem occurred"); 51} 52 DataRow row = table. rows [0]; 53 foreach (var prop in type. getProperties () 54 {55 prop. setValue (obj, row [prop. name]); 56} 57 return obj; 58} 59 60}

A prerequisite is that the class name must be the same as the database table name.

The Insert method adds the data corresponding to this class to the database table by passing a class Object. It mainly obtains the class name, attribute name, and attribute value through reflection, use these concatenated SQL statements to complete the insert operation.

The SelectById method queries data from the database and assigns values to the Object based on the class Type and attribute Id values. first, query data from the database, assign values to each attribute of the object through reflection, and return the object.

To specify the Type in advance, we can also change the SelectById method to a generic method.

// Query the public T SelectById Based on the Id <T> (int id) where T: new () // constructor with or without parameters under the generic constraint {Type type = typeof (T ); // object obj = Activator. createInstance (type); T obj = new T (); // select * from Person where Id = 1 string className = type. name; string SQL = "select * from" + className + "where Id = @ Id"; MySqlParameter para = new MySqlParameter ("@ Id", id); DataSet ds = MySqlHelper. executeDataset (connstr, SQL, para); DataTable table = ds. tables [0]; if (table. rows. count <= 0) {return default (T); // No data found} else if (table. rows. count> 1) {throw new Exception ("A big problem occurred");} DataRow row = table. rows [0]; foreach (var prop in type. getProperties () {prop. setValue (obj, row [prop. name]);} return obj; // T type}

 

Code called in the main program

1 // insert data to the database 2 Person p1 = new Person (); 3 MyORM orm = new MyORM (); 4 p1.Name = "Haha"; 5 p1.Age = 20; 6 orm. insert (p1); 7 Console. readKey (); 8 9 // Based on the query data 10 Person p2 = (Person) orm. selectById (typeof (Person), 1); 11 Console. writeLine (p2.Name); 12 Console. readKey (); 13 14 // query 15 Person P3 = orm by generic methods. selectById <Person> (1); 16 Console. writeLine (p3.Name); 17 Console. readKey ();

 

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.