首页 > 代码库 > 杨中科板的代码生成器源码板

杨中科板的代码生成器源码板

Form1.Designer.cs

namespace itcastcoder{    partial class Form1    {        /// <summary>        /// 必需的设计器变量。        /// </summary>        private System.ComponentModel.IContainer components = null;        /// <summary>        /// 清理所有正在使用的资源。        /// </summary>        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>        protected override void Dispose(bool disposing)        {            if (disposing && (components != null))            {                components.Dispose();            }            base.Dispose(disposing);        }        #region Windows 窗体设计器生成的代码        /// <summary>        /// 设计器支持所需的方法 - 不要        /// 使用代码编辑器修改此方法的内容。        /// </summary>        private void InitializeComponent()        {            this.label1 = new System.Windows.Forms.Label();            this.txtConnStr = new System.Windows.Forms.TextBox();            this.clbTables = new System.Windows.Forms.CheckedListBox();            this.cbGenerateDAL = new System.Windows.Forms.CheckBox();            this.checkBox2 = new System.Windows.Forms.CheckBox();            this.cbGenerateBLL = new System.Windows.Forms.CheckBox();            this.label2 = new System.Windows.Forms.Label();            this.cbGenerateModel = new System.Windows.Forms.CheckBox();            this.label3 = new System.Windows.Forms.Label();            this.label4 = new System.Windows.Forms.Label();            this.txtNameSpace = new System.Windows.Forms.TextBox();            this.txtOutPutDir = new System.Windows.Forms.TextBox();            this.folderBrowserDlOutputDir = new System.Windows.Forms.FolderBrowserDialog();            this.btnBrowseOutputDir = new System.Windows.Forms.Button();            this.btnGo = new System.Windows.Forms.Button();            this.txtLog = new System.Windows.Forms.TextBox();            this.btnConnect = new System.Windows.Forms.Button();            this.SuspendLayout();            //             // label1            //             this.label1.AutoSize = true;            this.label1.Location = new System.Drawing.Point(38, 26);            this.label1.Name = "label1";            this.label1.Size = new System.Drawing.Size(65, 12);            this.label1.TabIndex = 0;            this.label1.Text = "连接字符串";            //             // txtConnStr            //             this.txtConnStr.Location = new System.Drawing.Point(123, 23);            this.txtConnStr.Name = "txtConnStr";            this.txtConnStr.Size = new System.Drawing.Size(413, 21);            this.txtConnStr.TabIndex = 1;            this.txtConnStr.Text = "Data Source=stylee-pc\\mssqlserver2008;Initial Catalog=CallCenter;Integrated Secur" +                "ity=True";            //             // clbTables            //             this.clbTables.FormattingEnabled = true;            this.clbTables.Location = new System.Drawing.Point(12, 69);            this.clbTables.Name = "clbTables";            this.clbTables.Size = new System.Drawing.Size(134, 260);            this.clbTables.TabIndex = 3;            //             // cbGenerateDAL            //             this.cbGenerateDAL.AutoSize = true;            this.cbGenerateDAL.Checked = true;            this.cbGenerateDAL.CheckState = System.Windows.Forms.CheckState.Checked;            this.cbGenerateDAL.Location = new System.Drawing.Point(212, 79);            this.cbGenerateDAL.Name = "cbGenerateDAL";            this.cbGenerateDAL.Size = new System.Drawing.Size(66, 16);            this.cbGenerateDAL.TabIndex = 4;            this.cbGenerateDAL.Text = "生成DAL";            this.cbGenerateDAL.UseVisualStyleBackColor = true;            //             // checkBox2            //             this.checkBox2.AutoSize = true;            this.checkBox2.Checked = true;            this.checkBox2.CheckState = System.Windows.Forms.CheckState.Checked;            this.checkBox2.Location = new System.Drawing.Point(428, 79);            this.checkBox2.Name = "checkBox2";            this.checkBox2.Size = new System.Drawing.Size(78, 16);            this.checkBox2.TabIndex = 4;            this.checkBox2.Text = "checkBox1";            this.checkBox2.UseVisualStyleBackColor = true;            //             // cbGenerateBLL            //             this.cbGenerateBLL.AutoSize = true;            this.cbGenerateBLL.Checked = true;            this.cbGenerateBLL.CheckState = System.Windows.Forms.CheckState.Checked;            this.cbGenerateBLL.Location = new System.Drawing.Point(317, 79);            this.cbGenerateBLL.Name = "cbGenerateBLL";            this.cbGenerateBLL.Size = new System.Drawing.Size(66, 16);            this.cbGenerateBLL.TabIndex = 4;            this.cbGenerateBLL.Text = "生成BLL";            this.cbGenerateBLL.UseVisualStyleBackColor = true;            //             // label2            //             this.label2.AutoSize = true;            this.label2.Location = new System.Drawing.Point(38, 26);            this.label2.Name = "label2";            this.label2.Size = new System.Drawing.Size(65, 12);            this.label2.TabIndex = 0;            this.label2.Text = "连接字符串";            //             // cbGenerateModel            //             this.cbGenerateModel.AutoSize = true;            this.cbGenerateModel.Checked = true;            this.cbGenerateModel.CheckState = System.Windows.Forms.CheckState.Checked;            this.cbGenerateModel.Location = new System.Drawing.Point(428, 79);            this.cbGenerateModel.Name = "cbGenerateModel";            this.cbGenerateModel.Size = new System.Drawing.Size(78, 16);            this.cbGenerateModel.TabIndex = 4;            this.cbGenerateModel.Text = "生成Model";            this.cbGenerateModel.UseVisualStyleBackColor = true;            //             // label3            //             this.label3.AutoSize = true;            this.label3.Location = new System.Drawing.Point(167, 123);            this.label3.Name = "label3";            this.label3.Size = new System.Drawing.Size(53, 12);            this.label3.TabIndex = 0;            this.label3.Text = "命名空间";            //             // label4            //             this.label4.AutoSize = true;            this.label4.Location = new System.Drawing.Point(167, 157);            this.label4.Name = "label4";            this.label4.Size = new System.Drawing.Size(53, 12);            this.label4.TabIndex = 0;            this.label4.Text = "输出路径";            //             // txtNameSpace            //             this.txtNameSpace.Location = new System.Drawing.Point(226, 120);            this.txtNameSpace.Name = "txtNameSpace";            this.txtNameSpace.Size = new System.Drawing.Size(378, 21);            this.txtNameSpace.TabIndex = 1;            //             // txtOutPutDir            //             this.txtOutPutDir.Location = new System.Drawing.Point(226, 154);            this.txtOutPutDir.Name = "txtOutPutDir";            this.txtOutPutDir.Size = new System.Drawing.Size(378, 21);            this.txtOutPutDir.TabIndex = 1;            //             // btnBrowseOutputDir            //             this.btnBrowseOutputDir.Location = new System.Drawing.Point(610, 152);            this.btnBrowseOutputDir.Name = "btnBrowseOutputDir";            this.btnBrowseOutputDir.Size = new System.Drawing.Size(33, 23);            this.btnBrowseOutputDir.TabIndex = 2;            this.btnBrowseOutputDir.Text = "...";            this.btnBrowseOutputDir.UseVisualStyleBackColor = true;            this.btnBrowseOutputDir.Click += new System.EventHandler(this.btnBrowseOutputDir_Click);            //             // btnGo            //             this.btnGo.Location = new System.Drawing.Point(152, 181);            this.btnGo.Name = "btnGo";            this.btnGo.Size = new System.Drawing.Size(75, 23);            this.btnGo.TabIndex = 2;            this.btnGo.Text = "生成";            this.btnGo.UseVisualStyleBackColor = true;            this.btnGo.Click += new System.EventHandler(this.btnGo_Click);            //             // txtLog            //             this.txtLog.Location = new System.Drawing.Point(169, 210);            this.txtLog.Multiline = true;            this.txtLog.Name = "txtLog";            this.txtLog.Size = new System.Drawing.Size(435, 119);            this.txtLog.TabIndex = 1;            //             // btnConnect            //             this.btnConnect.Location = new System.Drawing.Point(568, 21);            this.btnConnect.Name = "btnConnect";            this.btnConnect.Size = new System.Drawing.Size(75, 23);            this.btnConnect.TabIndex = 2;            this.btnConnect.Text = "连接";            this.btnConnect.UseVisualStyleBackColor = true;            this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);            //             // Form1            //             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;            this.ClientSize = new System.Drawing.Size(688, 395);            this.Controls.Add(this.cbGenerateBLL);            this.Controls.Add(this.cbGenerateModel);            this.Controls.Add(this.checkBox2);            this.Controls.Add(this.cbGenerateDAL);            this.Controls.Add(this.clbTables);            this.Controls.Add(this.btnBrowseOutputDir);            this.Controls.Add(this.btnGo);            this.Controls.Add(this.btnConnect);            this.Controls.Add(this.label4);            this.Controls.Add(this.label3);            this.Controls.Add(this.label2);            this.Controls.Add(this.txtLog);            this.Controls.Add(this.txtOutPutDir);            this.Controls.Add(this.txtNameSpace);            this.Controls.Add(this.txtConnStr);            this.Controls.Add(this.label1);            this.Name = "Form1";            this.Text = "Form1";            this.Load += new System.EventHandler(this.Form1_Load);            this.ResumeLayout(false);            this.PerformLayout();        }        #endregion        private System.Windows.Forms.Label label1;        private System.Windows.Forms.TextBox txtConnStr;        private System.Windows.Forms.CheckedListBox clbTables;        private System.Windows.Forms.CheckBox cbGenerateDAL;        private System.Windows.Forms.CheckBox checkBox2;        private System.Windows.Forms.CheckBox cbGenerateBLL;        private System.Windows.Forms.Label label2;        private System.Windows.Forms.CheckBox cbGenerateModel;        private System.Windows.Forms.Label label3;        private System.Windows.Forms.Label label4;        private System.Windows.Forms.TextBox txtNameSpace;        private System.Windows.Forms.TextBox txtOutPutDir;        private System.Windows.Forms.FolderBrowserDialog folderBrowserDlOutputDir;        private System.Windows.Forms.Button btnBrowseOutputDir;        private System.Windows.Forms.Button btnGo;        private System.Windows.Forms.TextBox txtLog;        private System.Windows.Forms.Button btnConnect;    }}
From1.Designer.cs

Generator.cs

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data.SqlClient;using System.Data;using System.IO;using itcastcoder;namespace ItcastCoder{    class Generator    {        //在文本框中输入连接字符串        public static DataTable ExecuteDataTable(string connstr, string cmdText,            params SqlParameter[] parameters)        {            using (SqlConnection conn = new SqlConnection(connstr))            {                conn.Open();                using (SqlCommand cmd = conn.CreateCommand())                {                    cmd.CommandText = cmdText;                    cmd.Parameters.AddRange(parameters);                    using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))                    {                        DataTable dt = new DataTable();                        adapter.Fill(dt);                        return dt;                    }                }            }        }        //选择数据类型        private static Type GetTypeByDBType(string dbtype)        {            switch (dbtype.ToLower())            {                case "int":                    return typeof(int);                case "bigint":                    return typeof(long);                case "nvarchar":                case "char":                case "nchar":                case "varchar":                    return typeof(string);                case "bit":                    return typeof(bool);                case "datetime":                    return typeof(DateTime);                case "uniqueidentifier":                    return typeof(Guid);                default:                    return typeof(object);            }        }        //创建model层        public static void GenerateModel(string tablename, GeneratorArgs args)        {            DataTable dtCols = ExecuteDataTable(args.ConnectionString,                "select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@tablename",                        new SqlParameter("tablename", tablename));            StringBuilder sb = new StringBuilder();            sb.AppendLine("using System;");            sb.AppendLine("using System.Collections.Generic;");            sb.AppendLine("using System.Linq;");            sb.AppendLine("using System.Text;");            sb.AppendLine("namespace " + args.RootNamespace + ".Model");            sb.AppendLine("{");            sb.AppendLine("class " + tablename);            sb.AppendLine("{");            foreach (DataRow row in dtCols.Rows)            {                string colName = Convert.ToString(row["Column_Name"]);                string dataType = Convert.ToString(row["Data_Type"]);                sb.AppendLine("public " + GetTypeByDBType(dataType)                    + " " + colName + " { get; set; }");            }            sb.AppendLine("}");            sb.AppendLine("}");            string modelDir = Path.Combine(args.OutputDir, "Model");            string modelFile =                Path.Combine(modelDir, tablename + ".cs");            Directory.CreateDirectory(modelDir);            File.WriteAllText(modelFile, sb.ToString());        }        private static string[] GetCols(DataTable dtCols)        {            List<string> list = new List<string>();            foreach (DataRow row in dtCols.Rows)            {                string colName = Convert.ToString(row["Column_Name"]);                list.Add(colName);            }            return list.ToArray();        }        //移除Id        private static string[] GetColsWithoutId(DataTable dtCols)        {            List<string> list = new List<string>();            list.AddRange(GetCols(dtCols));            foreach (string colname in list.ToArray())            {                if (colname.Equals("id",                    StringComparison.CurrentCultureIgnoreCase))                {                    list.Remove(colname);                }            }            return list.ToArray();        }        //创建DAL层        public static void GenerateDAL(string tablename, GeneratorArgs args)        {            DataTable dtCols = ExecuteDataTable(args.ConnectionString,                "select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@tablename",                        new SqlParameter("tablename", tablename));            StringBuilder sb = new StringBuilder();            sb.AppendLine("using System;");            sb.AppendLine("using System.Collections.Generic;");            sb.AppendLine("using System.Linq;");            sb.AppendLine("using System.Text;");            sb.AppendLine("using " + args.RootNamespace + ".Model;");            sb.AppendLine("using System.Data.SqlClient;");            sb.AppendLine("using System.Data;");            sb.AppendLine("namespace " + args.RootNamespace + ".DAL");            sb.AppendLine("{");            sb.AppendLine("class " + tablename + "DAL");            sb.AppendLine("{");            {                sb.AppendLine("public int AddNew(" + tablename + " model){");                string[] cols = GetColsWithoutId(dtCols);                string[] colParams = (from col in cols                                      select "@" + col).ToArray();                sb.AppendLine("string sql = \"insert into " + tablename +                    "(" + string.Join(",", cols) +                    ") output inserted.id values(" +                    string.Join(",", colParams) + ")\";");                sb.AppendLine("int id = (int)SqlHelper.ExecuteScalar(sql");                foreach (string col in cols)                {                    sb.AppendLine(",new SqlParameter(\"" + col + "\", model." + col + ")");                }                sb.AppendLine(");");                sb.AppendLine("return id;");                sb.AppendLine("}");            }            {                sb.AppendLine("public bool Update(" + tablename + " model){");                string[] cols = GetColsWithoutId(dtCols);                string[] colParams = (from col in cols                                      select col + "=@" + col).ToArray();                sb.AppendLine("string sql = \"update " + tablename + " set " +                    string.Join(",", colParams) + " where id=@id\";");                sb.AppendLine("int rows = SqlHelper.ExecuteNonQuery(sql");                foreach (string col in GetCols(dtCols))                {                    sb.AppendLine(",new SqlParameter(\"" + col + "\", model." + col + ")");                }                sb.AppendLine(");");                sb.AppendLine("return rows > 0;}");            }            {                sb.AppendLine("public bool Delete(int id){");                sb.AppendLine("int rows = SqlHelper.ExecuteNonQuery(\"delete from" + " " + tablename + " where id=@id\",");                sb.AppendLine("new SqlParameter(\"id\",id));");                sb.AppendLine("return rows > 0;}");            }            {                sb.AppendLine("private static " + tablename +                    " ToModel(DataRow row){");                sb.AppendLine(tablename + " model = new "                    + tablename + "();");                foreach (DataRow row in dtCols.Rows)                {                    string colName = Convert.ToString(row["Column_Name"]);                    string dataType = Convert.ToString(row["Data_Type"]);                    sb.AppendLine("model." + colName + " = (" +                        GetTypeByDBType(dataType) + ")row[\"" + colName + "\"];");                }                sb.AppendLine("return model;}");            }            {                sb.AppendLine("public " + tablename + " Get(int id){");                sb.AppendLine("DataTable dt = SqlHelper.ExecuteDataTable(\"select * from "                    + tablename + "  where id=@id\",");                sb.AppendLine("new SqlParameter(\"id\",id));");                sb.AppendLine("if (dt.Rows.Count > 1)");                sb.AppendLine("{throw new Exception(\"more than 1 row was found\");}");                sb.AppendLine("if (dt.Rows.Count <= 0){return null;}");                sb.AppendLine("DataRow row = dt.Rows[0];");                sb.AppendLine(tablename + " model = ToModel(row);");                sb.AppendLine("return model;}");            }            {                sb.AppendLine("public IEnumerable<" + tablename                    + "> ListAll(){");                sb.AppendLine("List<" + tablename + "> list = new List<" +                    tablename + ">();");                sb.AppendLine("DataTable dt = SqlHelper.ExecuteDataTable(\"select * from " +                    tablename + "\");");                sb.AppendLine("foreach (DataRow row in dt.Rows){");                sb.AppendLine("list.Add(ToModel(row));}");                sb.AppendLine("return list;}");            }            sb.AppendLine("}");            sb.AppendLine("}");            string dalDir = Path.Combine(args.OutputDir, "DAL");            string dalFile =                Path.Combine(dalDir, tablename + "DAL.cs");            Directory.CreateDirectory(dalDir);            File.WriteAllText(dalFile, sb.ToString());        }        //创建BLL层        public static void GenerateBLL(string tablename, GeneratorArgs args)        {            DataTable dtCols = ExecuteDataTable(args.ConnectionString,                "select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@tablename",                        new SqlParameter("tablename", tablename));            StringBuilder sb = new StringBuilder();            sb.AppendLine("using System;");            sb.AppendLine("using System.Collections.Generic;");            sb.AppendLine("using System.Linq;");            sb.AppendLine("using System.Text;");            sb.AppendLine("using " + args.RootNamespace + ".Model;");            sb.AppendLine("using " + args.RootNamespace + ".DAL;");            sb.AppendLine("namespace " + args.RootNamespace + ".BLL");            sb.AppendLine("{");            sb.AppendLine("class " + tablename + "BLL{");            sb.AppendLine("public int AddNew(" + tablename + " model){");            sb.AppendLine("return new " + tablename + "DAL().AddNew(model);}");            sb.AppendLine("public bool Delete(int id){");            sb.AppendLine("return new " + tablename + "DAL().Delete(id);}");            sb.AppendLine("public bool Update(" + tablename + " model){");            sb.AppendLine("return new " + tablename + "DAL().Update(model);}");            sb.AppendLine("public " + tablename + " Get(int id){");            sb.AppendLine("return new " + tablename + "DAL().Get(id);}");            sb.AppendLine("public IEnumerable<" + tablename + "> ListAll(){");            sb.AppendLine("return new " + tablename + "DAL().ListAll();}");            sb.AppendLine("}}");            string bllDir = Path.Combine(args.OutputDir, "BLL");            string bllFile =                Path.Combine(bllDir, tablename + "BLL.cs");            Directory.CreateDirectory(bllDir);            File.WriteAllText(bllFile, sb.ToString());        }    }}
Generator.cs

GeneratorArgs.cs

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace itcastcoder{    class GeneratorArgs    {        public string RootNamespace { get; set; }        public string OutputDir { get; set; }        public string ConnectionString { get; set; }    }}
GeneratorArgs.cs

Program.cs

using System;using System.Collections.Generic;using System.Linq;using System.Windows.Forms;namespace itcastcoder{    static class Program    {        /// <summary>        /// 应用程序的主入口点。        /// </summary>        [STAThread]        static void Main()        {            Application.EnableVisualStyles();            Application.SetCompatibleTextRenderingDefault(false);            Application.Run(new Form1());        }    }}
Program.cs

 

杨中科板的代码生成器源码板