cnlan

常用链接

统计

最新评论

自动将表生成实体类...(以后将陆续推出自动生成数据访问层,业务逻辑层,WCF等)

最近做项目,发现很多事情都是重复劳动,突然自己想写一个适合自己的工具,自动生成代码....
做起来也比较简单,以下是一些关键性的代码,现在暂时推出直接将表生成实体类,同时自动添加注释...

 1using System;
 2using System.Collections.Generic;
 3using System.Windows.Forms;
 4using Microsoft.Data.ConnectionUI;
 5
 6namespace CodeBuilder
 7{
 8    static class Program
 9    {
10        /// <summary>
11        /// 应用程序的主入口点。
12        /// </summary>

13        [STAThread]
14        static void Main()
15        {
16            Application.EnableVisualStyles();
17            Application.SetCompatibleTextRenderingDefault(false);
18
19            DataConnectionDialog dialog = new DataConnectionDialog();
20            dialog.DataSources.Add(DataSource.SqlDataSource);
21            dialog.DataSources.Add(DataSource.OdbcDataSource);
22            dialog.DataSources.Add(DataSource.OracleDataSource);
23            dialog.DataSources.Add(DataSource.AccessDataSource);
24
25            dialog.SelectedDataSource = DataSource.SqlDataSource;
26            dialog.SelectedDataProvider = DataProvider.SqlDataProvider;
27            //
28            //如果确认,返回连接字符串,否则返回空
29            //
30            DataConnectionDialog.Show(dialog);
31            if (dialog.DialogResult == DialogResult.OK)
32            {
33                MainForm.ConnectionString = dialog.ConnectionString;
34                Application.Run(new MainForm());
35            }

36            else
37            {
38                Application.Exit();
39            }

40            
41        }

42

43



 

  1using System;
  2using System.Collections.Generic;
  3using System.ComponentModel;
  4using System.Data;
  5using System.Data.Common;
  6using System.Data.SqlClient;
  7using System.Drawing;
  8using System.Text;
  9using System.Windows.Forms;
 10
 11
 12namespace CodeBuilder
 13{
 14    public partial class MainForm : Form
 15    {
 16        public static string ConnectionString getset; }
 17        SqlConnection Conn = new SqlConnection(ConnectionString);
 18        private string RootNodeTag = "root";
 19        private string RootNodeText = "数据库";
 20 
 21
 22        public MainForm()
 23        {
 24            InitializeComponent();
 25        }

 26
 27        private void MainForm_Load(object sender, EventArgs e)
 28        {
 29            Conn.Open();
 30            List<Table> Tables = GetTables();
 31            TreeNode ParentNode = new TreeNode();
 32            ParentNode.Text = RootNodeText;
 33            ParentNode.Tag = RootNodeTag;
 34            foreach (Table T in Tables)
 35            {
 36                TreeNode TN = new TreeNode();
 37                TN.Text = T.TableName;
 38                TN.Tag = T;
 39                TN.ForeColor = Color.Blue;
 40                foreach (TableSchema TS in T.TableSchemas)
 41                {
 42                    TreeNode TN2 = new TreeNode();
 43                    TN2.Text = string.Format("{0}[{1}]", TS.ColumnName, TS.SqlTypeName);
 44                    TN2.Tag = TS;
 45                    TN.Nodes.Add(TN2);
 46                }

 47                ParentNode.Nodes.Add(TN);
 48            }

 49
 50
 51            this.TableTreeView.Nodes.Add(ParentNode);
 52        }

 53
 54
 55        /// <summary>
 56        /// 返回该表的主键
 57        /// </summary>
 58        /// <param name="TableName">需要获取主健的表名</param>
 59        /// <returns></returns>

 60        private List<string> GetTabkeKeys(string TableName)
 61        {
 62            SqlCommand command = new SqlCommand("sp_pkeys", Conn);
 63            command.CommandType = CommandType.StoredProcedure;
 64            SqlParameter para = new SqlParameter("table_name", TableName);
 65            command.Parameters.Add(para);
 66            List<string> TabkeKeys = new List<string>();
 67            using (SqlDataReader dr = command.ExecuteReader())
 68            {
 69                while (dr.Read())
 70                {
 71                    TabkeKeys.Add((string)dr["COLUMN_NAME"]);
 72                }

 73            }

 74            command.Dispose();            
 75            return TabkeKeys;
 76        }

 77
 78
 79        private List<Table> GetTables()
 80        {
 81            SqlCommand command = new SqlCommand("SELECT Name FROM sys.tables", Conn);
 82            List<Table> Tables = new List<Table>();
 83            using (SqlDataReader dr = command.ExecuteReader())
 84            {
 85                while (dr.Read())
 86                {
 87                    Table T = new Table();
 88                    T.TableName = (string)dr["Name"];             
 89                    Tables.Add(T);
 90                }

 91            }

 92            foreach (Table T in Tables)
 93            {
 94                T.TableKeys = GetTabkeKeys(T.TableName);
 95                T.TableSchemas = GetTableSchemas(T.TableName);
 96            }

 97            command.Dispose();
 98            return Tables;
 99        }

100
101
102        private List<TableSchema> GetTableSchemas(string TableName)
103        {
104            string sql = @"SELECT sys.columns.name AS ColumnName, 
105                type_name(sys.columns.system_type_id) AS SqlTypeName,
106                sys.columns.max_length AS MaxLength,
107                sys.columns.is_nullable AS IsNullable,
108                (select count(*) from sys.identity_columns where sys.identity_columns.object_id = sys.columns.object_id and sys.columns.column_id = sys.identity_columns.column_id) as IsIdentity, 
109                (select value from sys.extended_properties where sys.extended_properties.major_id = sys.columns.object_id and sys.extended_properties.minor_id = sys.columns.column_id) as Description
110                FROM sys.columns    
111                WHERE sys.columns.object_id = object_id(@TableName)
112                ORDER BY sys.columns.column_id";
113            SqlCommand command = new SqlCommand(sql, Conn);
114            command.Parameters.Add(new SqlParameter("TableName",TableName));
115            List<TableSchema> TableSchemas = new List<TableSchema>();
116            using (SqlDataReader dr = command.ExecuteReader())
117            {
118                while (dr.Read())
119                {
120                    TableSchema TS = new TableSchema();
121                    TS.ColumnName = (string)dr["ColumnName"];
122                    TS.Description = dr["Description"].ToString();
123                    TS.IsIdentity = Convert.ToBoolean(dr["IsIdentity"]);
124                    TS.MaxLength = (short)dr["MaxLength"];
125                    TS.SqlTypeName = (string)dr["SqlTypeName"];
126                    TableSchemas.Add(TS);
127                }

128            }

129            command.Dispose();
130            return TableSchemas;
131
132        }

133
134        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
135        {
136            if (Conn.State != ConnectionState.Closed)
137            {
138                Conn.Close();
139            }

140        }

141
142
143        /// <summary>
144        /// 生成实体类
145        /// </summary>
146        /// <param name="sender"></param>
147        /// <param name="e"></param>

148        private void BuildModelButton_Click(object sender, EventArgs e)
149        {
150            Table CurrentTable = this.TableTreeView.SelectedNode.Tag as Table;
151            
152            while (CurrentTable == null)
153            {
154                if (TableTreeView.SelectedNode.Tag.Equals(RootNodeTag))
155                {
156                    MessageBox.Show("请选择当前需要生成的表""提示");
157                    return;
158                }

159                CurrentTable = TableTreeView.SelectedNode.Parent.Tag as Table;                
160            }

161            StringBuilder ModelText = new StringBuilder();
162            //
163            //引用
164            //
165            ModelText.AppendLine("using System;");
166            ModelText.AppendLine("using System.Collections.Generic;");
167            ModelText.AppendLine();
168            //
169            //命名空间
170            //
171            if (string.IsNullOrEmpty(NamespaceTextEdit.Text))
172            {
173                ModelText.AppendLine("namespace Fengyun");
174            }

175            else
176            {
177           &nb