Try to write your own code generator

Source: Internet
Author: User

Based on the three-tier model, I installed yesterday's code and modified it to complete my own general code generator. Because I was a beginner and my professional courses took most of the time, I just tried to write some functions, but I still need to familiarize myself with some classes under I/O. So I am only writing here to make it easier to use as an exercise for future review. It is often not perfect and can be improved slowly, by learning the structure of the code generator and the three-tier mode, if I want to find the focus of the two learning, the focus is on the three-tier mode, but basically it depends on the ADO. NET implementation mechanism. If you are familiar with the two, the code generator is completely a data concatenation string operation, without the technical content.
Nowadays, there are many professional code generators. As a newbie, you should learn from the basics, instead of using code generators for enterprises such as CodeSmith and mobile software. Don't worry, in essence, I understand what he is doing. Due to the time relationship, I will temporarily paste a part of the code. After I finish writing it, I will summarize it.
First, I want to understand how to use the system database view in the following code. You will find everything very simple. Dear students, come on, general application development is not for scientific research, so there is nothing to learn. You only need to spend time and do not worship anyone. Everything is for your own purpose.
Code is not the most important. It is important to think about it. New users should not see controls, forms, but classes and objects one by one .....
Now let's paste the code below: The rest is very simple and will be completed in the past two days. The two messageboxes are for testing convenience and meaningless.
1 using System;
2 using System. Collections. Generic;
3 using System. ComponentModel;
4 using System. Data;
5 using System. Drawing;
6 using System. Text;
7 using System. Windows. Forms;
8 using System. Data. SqlClient;
9
10 namespace Code Generator
11 {
12 public partial class Form1: Form
13 {
14 public Form1 ()
15 {
16 InitializeComponent ();
17}
18
19 public DataTable ExecuteDataTable (string SQL, params SqlParameter [] paramers)
20 {
21 using (SqlConnection con = new SqlConnection (tb_Constr.Text ))
22 {
23 con. Open ();
24 using (SqlCommand cmd = con. CreateCommand ())
25 {
26 cmd. CommandText = SQL;
27 cmd. Parameters. AddRange (paramers );
28 DataTable dt = new DataTable ();
29 SqlDataAdapter adapter = new SqlDataAdapter (cmd );
30 adapter. Fill (dt );
31 return dt;
32}
33}
34}
35 /// <summary>
36 // convert the database field type to the C # character type
37 /// </summary>
38 // <param name = "dataType"> Field Type in the database </param>
39 // <returns> Field Type in C # </returns>
40 public static string StrToCsharp (string dataType)
41 {
42 switch (dataType)
43 {
44 case "int ":
45 return "int ";
46 case "nvarchar ":
47 case "varchar ":
48 case "char ":
49 case "nchar ":
50 return "string ";
51 case "bit ":
52 return "bool ";
53 case "datetime ":
54 return "DateTime ";
55 default:
56 return "object ";
57}
58}
59 // <summary>
60 // obtain the name of the table connected to the database
61 /// </summary>
62 // <param name = "sender"> </param>
63 // <param name = "e"> </param>
64 private void btn_Bulider_Click (object sender, EventArgs e)
65 {
66 DataTable Table = ExecuteDataTable ("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES ");
67 foreach (DataRow row in Table. Rows)
68 {
69 string TableName = row [0]. ToString ();
70 clb_TableName.Items.Add (TableName );
71}
72}
73 /// <summary>
74 // code generation button www.2cto.com
75 /// </summary>
76 private void btn_Bulider_Click_1 (object sender, EventArgs e)
77 {
78 // selected table
79 foreach (string TableName in clb_TableName.CheckedItems)
80 {
81 CreateModel (TableName );
82 CreateDAL (TableName );
83}
84
85}
86
87 private void CreateDAL (string TableName)
88 {
89 // assume that the primary key name is id
90 DataTable dt_column = ExecuteDataTable ("select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @ tablename and Column_Name <> 'id'", new SqlParameter ("tablename", TableName ));
91 string [] ColumnNames = new string [dt_column.Rows.Count]; // Save the field name in the table
92 for (int I = 0; I <dt_column.Rows.Count; I ++)
93 {
94 string colname = (string) dt_column.Rows [I] ["COLUMN_NAME"]; // obtain the column name
95 ColumnNames [I] = colname; // Add the column names obtained cyclically to the column name Array
96}
97 string [] paramers = new string [dt_column.Rows.Count];
98 for (int I = 0; I <paramers. Length; I ++)
99 {
100 paramers [I] = "@" + ColumnNames [I];
101}
102
103 StringBuilder sb = new StringBuilder ();
104 sb. AppendLine ("// Add operation ");
105 sb. AppendLine ("partial Class" + TableName + "DAL ");
106 sb. AppendLine ("{");
107 sb. AppendLine ("public static int AddNew (" + TableName + "model"); // return the primary key of the newly added field ");
108 sb. AppendLine ("{");
109 sb. AppendLine ("object obj = SQLHelper. ExecuteScalar (");
110 sb. appendLine ("\" insert into "+ TableName +" ("+ string. join (",", ColumnNames) + ") output inserted. id values ("+ string. join (",", paramers) + ")\"");
111 foreach (string colname in ColumnNames)
112 {
113 sb. AppendLine (", new SqlParameter (\" "+ colname +" \ ", model." + colname + ")");
114}
115 sb. AppendLine (");");
116 sb. AppendLine ("return Convert. ToInt32 (obj );");
117 MessageBox. Show (sb. ToString ());
118}
119
120 /// <summary>
121 // generate the Model
122 /// </summary>
123 /// <param name = "TableName"> name of the selected table </param>
124 /// <returns> model </returns>
125 private void CreateModel (string TableName)
126 {
127 DataTable dt_column = ExecuteDataTable ("select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @ tablename and Column_Name <> 'id'", new SqlParameter ("tablename", TableName ));
128 StringBuilder sb = new StringBuilder ();
129 sb. AppendLine ("Class" + TableName );
130 sb. AppendLine ("{");
131 foreach (DataRow row in dt_column.Rows)
132 {
133 string dt_Col = (string) row ["COLUMN_NAME"];
134 string col_Type = (string) row ["DATA_TYPE"];
135 string CsType = StrToCsharp (col_Type );
136 sb. AppendLine ("Public" + CsType + "" + dt_Col + "{get; set ;}");
137}
138 sb. AppendLine ("}");
139 // MessageBox. Show (sb. ToString ());
140}
141}
142}

 

Author: Xie xiaoge
 

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.