C # code generator that automatically generates data object code and crud operations

Source: Internet
Author: User

I recently developed a C # code generator on vs2005 and sqlserver2005 platforms, supporting direct ing between database tables and C # data objects, and automatic generation of CRUD operation code, you only need to implement the idal interface. This tool can significantly improve the development speed and free developers from the heavy coding of database table object encapsulation. Now, the core processing code is published, for reference only:

/// Data object extraction the conversion process between some database types and C # Object Types
Private string convertsqldatareader (string sqlreader, string type, int I)
{
Switch (type. Trim (). tolower ())
{
Case "bigint": Return sqlreader + ". getint64 (" + I. tostring () + ")";
// Case "binary": Return sqlreader + ". getvalue (" + I. tostring () + ")";
Case "bit": Return sqlreader + ". getboolean (" + I. tostring () + ")";
Case "char": Return sqlreader + ". getstring (" + I. tostring () + ")";
Case "datetime": Return sqlreader + ". getdatetime (" + I. tostring () + ")";
Case "decimal": Return sqlreader + ". getdecimal (" + I. tostring () + ")";
Case "float": Return sqlreader + ". getfloat (" + I. tostring () + ")";
// Case "image": Return sqlreader + ". getvalue (" + I. tostring () + ")";
Case "int": Return sqlreader + ". getint32 (" + I. tostring () + ")";
Case "money": Return sqlreader + ". getdecimal (" + I. tostring () + ")";
Case "nchar": Return sqlreader + ". getstring (" + I. tostring () + ")";
Case "ntext": Return sqlreader + ". getstring (" + I. tostring () + ")";
Case "nvarchar": Return sqlreader + ". getstring (" + I. tostring () + ")";
Case "real": Return sqlreader + ". getfloat (" + I. tostring () + ")";
Case "smalldatetime": Return sqlreader + ". getdatetime (" + I. tostring () + ")";
Case "smallint": Return sqlreader + ". getint16 (" + I. tostring () + ")";
Case "smallmoney": Return sqlreader + ". getdecimal (" + I. tostring () + ")";
Case "text": Return sqlreader + ". getstring (" + I. tostring () + ")";
Case "timestamp": Return sqlreader + ". getdatetime (" + I. tostring () + ")";
Case "tinyint": Return sqlreader + ". getbyte (" + I. tostring () + ")";
Case "UDT": Return sqlreader + ". getvalue (" + I. tostring () + ")";
Case "uniqueidentifier": Return sqlreader + ". getguid (" + I. tostring () + ")";
// Case "varbinary": Return sqlreader + ". getvalue (" + I. tostring () + ")";
Case "varchar": Return sqlreader + ". getstring (" + I. tostring () + ")";
Case "variant": Return sqlreader + ". getvalue (" + I. tostring () + ")";
Case "XML": Return sqlreader + ". getstring (" + I. tostring () + ")";
Case "numeric": Return sqlreader + ". getdecimal (" + I. tostring () + ")";
Default: Throw new argumentexception (Type + "not in itabby. Product. sqlcode. sqlcode. convertgetmethod Process List .");
}
}
/// Restore the database type with a fully qualified name
Private string convertsqldbtype (string type)
{

Switch (type. Trim (). tolower ())
{
Case "bigint": Return "system. Data. sqldbtype. bigint ";
Case "binary": Return "system. Data. sqldbtype. Binary ";
Case "bit": Return "system. Data. sqldbtype. Bit ";
Case "char": Return "system. Data. sqldbtype. Char ";
Case "datetime": Return "system. Data. sqldbtype. datetime ";
Case "decimal": Return "system. Data. sqldbtype. Decimal ";
Case "float": Return "system. Data. sqldbtype. Float ";
Case "image": Return "system. Data. sqldbtype. Image ";
Case "int": Return "system. Data. sqldbtype. int ";
Case "money": Return "system. Data. sqldbtype. Money ";
Case "nchar": Return "system. Data. sqldbtype. nchar ";
Case "ntext": Return "system. Data. sqldbtype. ntext ";
Case "nvarchar": Return "system. Data. sqldbtype. nvarchar ";
Case "real": Return "system. Data. sqldbtype. Real ";
Case "smalldatetime": Return "system. Data. sqldbtype. smalldatetime ";
Case "smallint": Return "system. Data. sqldbtype. smallint ";
Case "smallmoney": Return "system. Data. sqldbtype. smallmoney ";
Case "text": Return "system. Data. sqldbtype. Text ";
Case "timestamp": Return "system. Data. sqldbtype. timestamp ";
Case "tinyint": Return "system. Data. sqldbtype. tinyint ";
Case "UDT": Return "system. Data. sqldbtype. UDT ";
Case "uniqueidentifier": Return "system. Data. sqldbtype. uniqueidentifier ";
Case "varbinary": Return "system. Data. sqldbtype. varbinary ";
Case "varchar": Return "system. Data. sqldbtype. varchar ";
Case "variant": Return "system. Data. sqldbtype. Variant ";
Case "XML": Return "system. Data. sqldbtype. xml ";
Case "numeric": Return "system. Data. sqldbtype. Decimal ";
Default: Throw new argumentexception (Type + "not in itabby. Product. sqlcode. sqlcode. convertsqldbtype Process List .");
}
}
/// Load the database table object
Public arraylist loadtables (string sconnectionstring)
{

Using (system. Data. sqlclient. sqlconnection conn = new system. Data. sqlclient. sqlconnection (convertconnectionstring (sconnectionstring )))
{
_ Stables. Clear ();
Conn. open ();
System. Data. sqlclient. sqlcommand cmd = conn. createcommand ();
Cmd. commandtext = "select table_name from information_schema.tables where table_type = 'base table' order by table_name ";
System. Data. sqlclient. sqldatareader DR = cmd. executereader ();
While (dr. Read ())
{
_ Stables. Add (dr. getstring (0 ));
}
Dr. Close ();
Conn. Close ();
}
Return _ stables;
}

/// Load the database column object
Public arraylist loadcolumns (string sconnectionstring, string stable)
{
Using (system. Data. sqlclient. sqlconnection conn = new system. Data. sqlclient. sqlconnection (convertconnectionstring (sconnectionstring )))
{
_ Scolumns. Clear ();
Conn. open ();
System. Data. sqlclient. sqlcommand cmd = conn. createcommand ();
/// Get PK in current table
Cmd. commandtext = "select column_name from information_schema. key_column_usage where table_name = '"+ stable +"' and constraint_name in (Select name from sys. objects where parent_object_id = (select object_id ('"+ stable +"') and type = 'pk ')";
System. Data. sqlclient. sqldatareader DR = cmd. executereader ();
Arraylist PKS = new arraylist ();
While (dr. Read ())
{
PKS. Add (dr. getstring (0 ));
}
Dr. Close ();
/// Get columns in current table
Cmd. commandtext = "select column_name, data_type, character_maximum_length, numeric_precision, numeric_scale, columnproperty (object_id ('" + stable + "'), column_name, 'isidentity ') from information_schema.columns where table_name = '"+ stable +" 'order by column_name ";
Dr = cmd. executereader ();
Bool PK = false;
While (dr. Read ())
{
/// PK
Foreach (string s in PKS)
{
If (S. Equals (dr. getstring (0 )))
{
PK = true;
}
}
_ Scolumns. Add (dr. getstring (0) + ";" + dr. getstring (1) + ";" + convert. tostring (dr. isdbnull (2 )? String. Empty: dr. getvalue (2). tostring () + ";" + convert. tostring (dr. isdbnull (3 )? String. Empty: dr. getvalue (3). tostring () + ";" + convert. tostring (dr. isdbnull (4 )? String. empty: Dr. getvalue (4 ). tostring () + ";" + PK. tostring () + ";" + dr. getvalue (5 ). equals (1 ). tostring ());
PK = false;
}
Dr. Close ();
Conn. Close ();
}
Return _ scolumns;
}
/// Load a Data Object
Public String getobjectcode (string sconnectionstring, string stable, arraylist columns, bool [] operations)
{
System. Text. stringbuilder sobjectcode = new stringbuilder ();
Sobjectcode. append (using_declare + "/R/N" + namespace_declare + "/R/N" + namespace_begin + "/R/N ");
Sobjectcode. append ("/t" + class_declare + stable + "/R/n/t" + class_body_begin + "/R/N ");
Using (system. Data. sqlclient. sqlconnection conn = new system. Data. sqlclient. sqlconnection (convertconnectionstring (sconnectionstring )))
{
System. Data. sqlclient. sqldataadapter adpt = new system. Data. sqlclient. sqldataadapter ("select top 1 * from" + stable, Conn );
Datatable Cols = new datatable ();
Adpt. Fill (Cols );
Sobjectcode. append ("/T" + region_begin + "attribute block" + "/R/N ");
If (Operations [0])
{
Foreach (system. Data. datacolumn column in cols. columns)
{
/// Private var;
Sobjectcode. append ("/T" + column. datatype. fullname + "_" + column. columnname + ";" + "/R/N ");
/// Attribute
Sobjectcode. append ("/T/tpublic" + column. datatype. fullname + "" + column. columnname. toupper () + attribute_begin );
/// Get
Sobjectcode. append (get_attribute_begin + "return" + "_" + column. columnname + ";");
Sobjectcode. append (get_attribute_end );
/// Set
Sobjectcode. append (set_attribute_begin + "_" + column. columnname + "= value ;");
Sobjectcode. append (set_attribute_end );
Sobjectcode. append (attribute_end + "/R/N ");
}
}
Sobjectcode. append ("/T" + region_end );
Sobjectcode. append ("/R/n/T" + region_begin + "method Blok ");
/// Add operation
If (Operations [1]) sobjectcode. append (getaddcode ("dataobject _" + stable, columns ));
/// Update operation
If (Operations [2]) sobjectcode. append (getupdatecode ("dataobject _" + stable, columns ));
/// Delete operation
If (Operations [3]) sobjectcode. append (getdeletecode ("dataobject _" + stable, columns ));
/// Select Operation
If (Operations [4]) sobjectcode. append (getgetcode ("dataobject _" + stable, columns ));
/// List Operation
If (Operations [5]) sobjectcode. append (getlistcode ("dataobject _" + stable, columns ));
Sobjectcode. append ("/R/n/T" + region_end );
}
Sobjectcode. append ("/R/n/t" + class_body_end );
Sobjectcode. append ("/R/N" + namespace_end );
Return sobjectcode. tostring ();

}

/// Generate the add method code
Private string getaddcode (string sobject, arraylist columns)
{
System. Text. stringbuilder sobjectcode = new stringbuilder ();
Sobjectcode. append ("/R/n/T/tpublic static int add (" + sobject + "OBJ, idal, sqltransaction trans )");
Sobjectcode. append ("/R/n/T {");
Sobjectcode. append ("/R/n/T/tconst string ssql =/" insert into "+ sobject. substring (11 ));
Sobjectcode. append ("(");
Int Ikey = 0;
Foreach (string s in columns)
{
/// All columns without identity Columns
If (S. Split (';') [6]. tolower (). Equals ("true") continue;
Sobjectcode. append ("" + S. Split (';') [0] + ",");
Ikey + = 1;
}
Sobjectcode. Remove (sobjectcode. Length-1, 1 );
Sobjectcode. append (")");
Sobjectcode. append ("values ");
Sobjectcode. append ("(");
Foreach (string s in columns)
{
/// All columns without identity Columns
If (S. Split (';') [6]. tolower (). Equals ("true") continue;
Sobjectcode. append ("@" + S. Split (';') [0] + ",");
}
Sobjectcode. Remove (sobjectcode. Length-1, 1 );
Sobjectcode. append (")");
Sobjectcode. append (";/";/R/N ");
Sobjectcode. append ("/T" + region_begin + "parameters block" + "/R/N ");
Sobjectcode. append ("/T/tsqlparameter [] parameters = new sqlparameter [" + Ikey + "];/R/N ");
Ikey = 0;
For (INT I = 0; I <columns. Count; I ++)
{
/// All columns without identity Columns
If (columns [I]. tostring (). Split (';') [6]. tolower (). Equals ("true") continue;
Sobjectcode. append ("/T/tparameters [" + Ikey + "] = new sqlparameter ();/R/N ");
Sobjectcode. append ("/T/tparameters [" + Ikey + "]. parametername =/"@" + columns [I]. tostring (). split (';') [0] + "/";/R/N ");
If (columns [I]. tostring (). Split (';') [2]. Equals (string. Empty ))
{
If (! Columns [I]. tostring (). Split (';') [3]. Equals (string. Empty ))
{
Sobjectcode. append ("/T/tparameters [" + Ikey + "]. size = "+ columns [I]. tostring (). split (';') [3] + ";/R/N ");
}
}
Else
{
Sobjectcode. append ("/T/tparameters [" + Ikey + "]. size = "+ columns [I]. tostring (). split (';') [2] + ";/R/N ");
}
Sobjectcode. append ("/T/tparameters [" + Ikey + "]. sqldbtype = "+ convertsqldbtype (columns [I]. tostring (). split (';') [1]) + ";/R/N ");
Sobjectcode. append ("/T/tparameters [" + Ikey + "]. value = obj. "+ columns [I]. tostring (). split (';') [0]. toupper () + ";/R/N ");
Ikey + = 1;
}
Sobjectcode. append ("/T" + region_end + "/R/N ");
Sobjectcode. append ("/T/treturn idal. executenonquery (ssql, parameters, trans );");
Sobjectcode. append ("/R/n/T }");
Return sobjectcode. tostring ();
}

 

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.