Write the ORM framework by yourself (7): implement the Save Method for new functions

Source: Internet
Author: User

In the previous article, we talked about the FindById Method Based on the ID query function. Next we will implement the Save method function. The Code is as follows: 1-1:

# Region saves entity data to the database public int Save <T> (T entity ){
// Obtain the table information required to add new data from the object class and save it to TableInfo tableInfo = DbEntityUtils in the TableInfo object. getTableInfo (entity, DbOperateType. INSERT); // generate the new SQL statement based on the data in the tableInfo object
String strSql = DbEntityUtils. GetInsertSql (tableInfo); // create a parameter Array Based on the number of Columns in tableInfo
IDbDataParameter [] parms = DbFactory. CreateDbParameters (tableInfo. Columns. Count); // set the data in the Columns set in the tableInfo object to the parameter Array
    DbEntityUtils.SetParameters(tableInfo.Columns, parms);        
// Execute the SQL command object val = AdoHelper. ExecuteNonQuery (transaction, CommandType. Text, strSql, parms); // return the number of affected rows
    return Convert.ToInt32(val);}#endregion

In code 1-1, the DbEntityUtils. GetTableInfo method has been analyzed in the FindById method for implementing the query function.

Code string strSql = DbEntityUtils. GetInsertSql (tableInfo); In DbEntityUtils. GetInsertSql, the code is 1-2:

Public static string GetInsertSql (TableInfo tableInfo) {StringBuilder sbColumns = new StringBuilder (); StringBuilder sbValues = new StringBuilder (); // store the name and value of IDs in tableInfo into the Columns set
TableInfo. Columns. Put (tableInfo. Id. Key, tableInfo. Id. Value); foreach (string key in tableInfo. Columns. Keys) {if (! String. IsNullOrEmpty (key. Trim () {// generate an SQL statement based on the key in the Columns set. For example:
            //strsql = “insert into student(studentid,studentno,name) values((@studentid,@studentno,@name)”;
            object value = tableInfo.Columns[key];            sbColumns.Append(key).Append(",");            sbValues.Append(AdoHelper.DbParmChar).Append(key).Append(",");        }    }    sbColumns.Remove(sbColumns.ToString().Length - 1, 1);    sbValues.Remove(sbValues.ToString().Length - 1, 1);    string strSql = "INSERT INTO {0}({1}) VALUES({2})";    strSql = string.Format(strSql, tableInfo.TableName, sbColumns.ToString(), sbValues.ToString());    return strSql;}

Code 1-1: IDbDataParameter [] parms = DbFactory. CreateDbParameters (tableInfo. Columns. Count );

Create a parameter array of the specified size and create a parameter Array Based on different database types. The Code is as follows: 1-3:

// <Summary> // create a parameter array object for the database based on the database type configured in the configuration file // and input parameters. // </summary> // <returns> </returns> public static IDbDataParameter [] CreateDbParameters (int size) {int I = 0; IDbDataParameter [] param = null; switch (AdoHelper. dbType) {case DatabaseType. SQLSERVER: param = new SqlParameter [size]; while (I <size) {param [I] = new SqlParameter (); I ++;} break; case DatabaseType. ORACLE: param = new OracleParamet Er [size]; while (I <size) {param [I] = new OracleParameter (); I ++;} break; case DatabaseType. ACCESS: param = new OleDbParameter [size]; while (I <size) {param [I] = new OleDbParameter (); I ++;} break; default: throw new Exception ("the database type is not supported currently! ");} Return param ;}
Code 1-1: DbEntityUtils. SetParameters (tableInfo. Columns, parms );
Assign the data in the tableInfo. Columns set to the parameter array. The Code is as follows: 1-4:
public static void SetParameters(ColumnInfo columns, params IDbDataParameter[] parms){    int i = 0;    foreach (string key in columns.Keys)    {        if (!string.IsNullOrEmpty(key.Trim()))        {            parms[i].ParameterName = key;            parms[i].Value = columns[key];            i++;        }    }}

At this point, the main code of the Save method has been completed, and all that is not mentioned have been analyzed before. The TableInfo class is used multiple times above. The TableInfo code will be pasted below:

Using System; using System. Collections. Generic; using System. Text; using System. Collections; namespace System. Orm. Common {public class TableInfo {// variable that stores the table name
         private string tableName;       
// Store the variables in the primary key generation mode
        private int strategy;
 
// Object that stores the Id column name and column Value
         private IdInfo id = new IdInfo();        
// A set of column names and column values
         private ColumnInfo columns = new ColumnInfo();        
// A set of Object Relationships of attribute names and column names
         private Map propToColumn = new Map();                public Map PropToColumn        {            get { return propToColumn; }            set { propToColumn = value; }        }         public string TableName        {            get { return tableName; }            set { tableName = value; }        }

Public int Strategy
{
Get {return strategy ;}
Set {strategy = value ;}
}

                public IdInfo Id        {            get { return id; }            set { id = value; }        }                                public ColumnInfo Columns        {            get { return columns; }            set { columns = value; }        }    }}

Code of the ColumnInfo class:

using System;using System.Collections;using System.Collections.Generic;using System.Text;namespace System.Orm.Common{    public class ColumnInfo : Map    {                   }}

IdInfo code:

using System;using System.Collections.Generic;using System.Text;namespace System.Orm.Common{    public class IdInfo    {        private string key;        private object value;        public string Key        {            get { return key; }            set { key = value; }        }                public object Value        {            get { return this.value; }            set { this.value = value; }        }    }}

Map code:

using System;using System.Collections.Generic;using System.Text;using System.Collections;namespace System.Orm.Common{    public class Map : Hashtable    {        public void Put(object key,object value)        {            this.Add(key, value);        }          }}

The Code required for the Save method is already on it.

Technorati label: ORM
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.