C # code generator for automatically generating data object code and CRUD operations

Source: Internet
Author: User
Tags foreach bool continue empty generator split tostring trim
Objects | data

The author recently developed a C # code generator on the VS2005 platform and SqlServer2005 platform, which supports the direct mapping of database tables and C # Data objects, as well as the automatic generation of CRUD operation code, the user only needs to implement the Idal interface, the tool can significantly improve the development speed, Let developers free from the Heavy database Table Object Encapsulation Code (tool download Address: http://itabby.com/index-5.asp), the core processing code is published, for reference only:

Data object extracts 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.");
}
}
Database type fully qualified name restore
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.");
}
}
Loading database Table objects
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;
}

Loading database Column objects
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_obje ct_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\t" + Region_begin + "Attribute block" + "\ r \ n");
if (Operations[0])
{
foreach (System.Data.DataColumn column in cols. Columns)
{
private Var;
Sobjectcode.append ("\t\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\t" + region_end);
Sobjectcode.append ("\r\n\t\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\t" + region_end);
}
Sobjectcode.append ("\r\n\t" + class_body_end);
Sobjectcode.append ("\ r \ n" + namespace_end);
return sobjectcode.tostring ();

}

Generate 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 idal,sqltransaction trans)");
Sobjectcode.append ("\r\n\t\t{");
Sobjectcode.append ("\r\n\t\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\t\t" + Region_begin + "Parameters block" + "\ r \ n");
Sobjectcode.append ("\t\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\t\tparameters[" + Ikey + "] = new SqlParameter (); \ r \ n");
Sobjectcode.append ("\t\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\t\tparameters[" + Ikey + "]. Size = "+ columns[i]. ToString (). Split (';') [3] + "; \ r \ n");
}
}
Else
{
Sobjectcode.append ("\t\t\tparameters[" + Ikey + "]. Size = "+ columns[i]. ToString (). Split (';') [2] + "; \ r \ n");
}
Sobjectcode.append ("\t\t\tparameters[" + Ikey + "]. SqlDbType = "+ Convertsqldbtype (columns[i). ToString (). Split (';') [1]) + "; \ r \ n");
Sobjectcode.append ("\t\t\tparameters[" + Ikey + "]. Value = obj. "+ columns[i]. ToString (). Split (';') [0]. ToUpper () + "; \ r \ n");
Ikey + 1;
}
Sobjectcode.append ("\t\t\t" + region_end + "\ r \ n");
Sobjectcode.append ("\t\t\treturn idal.") ExecuteNonQuery (Ssql,parameters,trans); ");
Sobjectcode.append ("\r\n\t\t}");
return sobjectcode.tostring ();
}



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.