. Net write a simple ORM (hands-on) and. netorm

Source: Internet
Author: User

. Net write a simple ORM (hands-on) and. netorm

As we all know,. Net is EF and some other ORM has been transplanted from JAVA.

No matter what additional messy Functions The ORM provides

But the most important thing is link ing.

I have been using ORMDapper, a very small ORM. The first time I saw this ORM, someone posted a ranking on the common ORM efficiency in a post. I tried it myself and then I saw ORMDapper.

This is to make the best of lightweight! There is only one 96 kb Class file. There are many spaces and comments.

JAVA is more interesting than. NET recently. It can also be used in JAVA for future. NET failures.

 

Directly run the Code:

 

Private static string ConnectionString = "**"; /// <summary> // update the data directly if no SQL parameter is specified. // </summary> // <param name = "SQL"> the SQL statement to be executed </param> /// <param name = "o"> the passed object class requires that the fields in this class must be consistent with the SQL parameter name and are case insensitive </param> /// <returns> </returns> public static int UpdateModel (string SQL, object o) {var s = SQL. split ('@'); return Update (SQL, s. length = 1? Null: GetSqlParameters (o, s ));} /// <summary> /// query data /// </summary> /// <typeparam name = "T"> ing object class </typeparam> /// <param name = "SQL"> the executed SQL statement </param> // <param name = "o"> the passed object class requires that the fields in the class must match the SQL parameters. names are consistent and Case Insensitive </param> /// <returns> </returns> public static List <T> SeleteModel <T> (string SQL, object o) where T: class, new () {var s = SQL. split ('@'); return Select <T> (SQL, s. length = 1? Null: GetSqlParameters (o, s ));} /// <summary> /// dynamically create the SqlParameter object // </summary> /// <param name = "o"> the passed object class object requires the fields in the class the SQL parameter name must be the same as the SQL parameter name. It must be case insensitive </param> /// <param name = "s"> the SQL statement after cutting </param> /// <returns> </returns> private static SqlParameter [] GetSqlParameters (object o, string [] s) {s = s. select (c => c. split ('') [0]. trim ()). toArray (); Type t = o. getType (); if (t = typeof (object) throw new Exc Eption ("the type passed by UpdateModel is the OBJECT type"); // The reflected read field verifies whether it is the SQL parameter var tlist = t. getFields (BindingFlags. public | BindingFlags. instance ). where (c => c. getValue (o )! = Null & s. FirstOrDefault (a => a. ToLower () = c. Name. ToLower ())! = Null). ToList (); // determine whether the obtained data is consistent with the required data quantity if (tlist. Count ()! = S. count ()-1) throw new Exception ("the number of passed object Value parameters is not equal to the number required in SQL"); SqlParameter [] sp = new SqlParameter [tlist. count ()]; for (int I = 0; I <s. length-1; I ++) {sp [I] = new SqlParameter (s [I + 1]. trim (), tlist. firstOrDefault (c => c. name. toLower () = s [I + 1]. toLower ()). getValue (o);} return sp;} private static List <T> SeleteModel <T> (SqlDataReader data) where T: class, new () {// obtain the number of columns int iFie LdCount = data. fieldCount; List <T> list = new List <T> (); while (data. read () {T tType = new T (); for (int I = 0; I <iFieldCount; I ++) {// reflection injection field value string dataName = data. getName (I); FieldInfo fie = tType. getType (). getField (dataName); if (fie = null) continue; fie. setValue (tType, data [dataName]);} list. add (tType) ;}return list;} private static List <T> Select <T> (string SQL, SqlParameter [] sp) Where T: class, new () {using (SqlConnection conn = new SqlConnection (ConnectionString) {using (SqlCommand com = new SqlCommand (SQL, conn) {conn. open (); if (sp! = Null) com. parameters. addRange (sp); return SeleteModel <T> (com. executeReader () ;}} private static int Update (string SQL, SqlParameter [] sp) {using (SqlConnection conn = new SqlConnection (ConnectionString )) {using (SqlCommand com = new SqlCommand (SQL, conn) {conn. open (); if (sp! = Null) com. Parameters. AddRange (sp); return com. ExecuteNonQuery ();}}}

Call example:

 public class TestCalss    {        public static void Main()        {            string sql = @"SELECT TOP 1000 [ID]                           ,[ExpressID]                          ,[OrderID]                          ,[MailCode]                           ,[SendXML]                          ,[SendFlag]                          ,[SendCount]                       FROM [SendStateTest]  where id=@id  and SendXML=@SendXML  ";            string sql2 = @"update [DangDang_SendStateTest] set  SendXML='0000' where id=@id     ";             int i = AdoConnection.UpdateModel(sql2, new Na() { ID = 1 });            List<Na> a = AdoConnection.SeleteModel<Na>(sql, new Na() { ID = 1, SendXML = "0000" });            Console.WriteLine(a);         }        public class Na        {             public int ID;             public string ExpressID;             public string OrderID;             public string MailCode;              public string SendXML;             public int SendFlag;             public int SendCount;        }     }

  

It only provides a simple ORM method.

To be honest, it's not as good as the ORM framework that everyone is using on the Internet.

It can be processed and expanded on this simple ORM, such as supporting the storage process without specifying the database SQL statement category, etc.

If you are interested, you can do it yourself.

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.