From 806d6d2e9c4736e0e56639e13b01fde971986f7c Mon Sep 17 00:00:00 2001 From: forget-the-bright Date: Tue, 22 Aug 2023 17:57:39 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=A8=A1=E6=9D=BF=E5=A1=AB?= =?UTF-8?q?=E5=85=85=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DatabasetoEntityclass/Class1.cs | 13 - .../DatabasetoEntityclass.csproj | 15 +- DatabasetoEntityclass/Form1.Designer.cs | 3 +- DatabasetoEntityclass/Form1.cs | 348 +++++++----------- DatabasetoEntityclass/Program.cs | 2 +- .../Properties/Resources.Designer.cs | 56 ++- .../Properties/Settings.Designer.cs | 30 +- .../Template/ModelFile.template | 28 ++ DatabasetoEntityclass/{ => Util}/DbHelper.cs | 2 +- DatabasetoEntityclass/Util/DbUtil.cs | 240 ++++++++++++ DatabasetoEntityclass/packages.config | 16 + 11 files changed, 459 insertions(+), 294 deletions(-) delete mode 100644 DatabasetoEntityclass/Class1.cs create mode 100644 DatabasetoEntityclass/Template/ModelFile.template rename DatabasetoEntityclass/{ => Util}/DbHelper.cs (99%) create mode 100644 DatabasetoEntityclass/Util/DbUtil.cs create mode 100644 DatabasetoEntityclass/packages.config diff --git a/DatabasetoEntityclass/Class1.cs b/DatabasetoEntityclass/Class1.cs deleted file mode 100644 index 674e89e..0000000 --- a/DatabasetoEntityclass/Class1.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace WindowsFormsApp1 -{ - internal class Class1 - { - - } -} diff --git a/DatabasetoEntityclass/DatabasetoEntityclass.csproj b/DatabasetoEntityclass/DatabasetoEntityclass.csproj index c2fb37d..9739c85 100644 --- a/DatabasetoEntityclass/DatabasetoEntityclass.csproj +++ b/DatabasetoEntityclass/DatabasetoEntityclass.csproj @@ -6,8 +6,8 @@ AnyCPU {7D7B530A-23A4-4024-B263-A942AA53DCC5} WinExe - WindowsFormsApp1 - WindowsFormsApp1 + GenerateClass + GenerateClass v4.7.2 512 true @@ -39,6 +39,9 @@ ..\packages\Google.Protobuf.3.21.9\lib\net45\Google.Protobuf.dll + + ..\packages\JinianNet.JNTemplate.2.3.3\lib\net46\JinianNet.JNTemplate.dll + ..\packages\K4os.Compression.LZ4.1.3.5\lib\net462\K4os.Compression.LZ4.dll @@ -86,8 +89,7 @@ - - + Form @@ -96,6 +98,7 @@ + Form1.cs @@ -107,6 +110,7 @@ True Resources.resx + True @@ -118,6 +122,9 @@ Settings.settings True + + PreserveNewest + diff --git a/DatabasetoEntityclass/Form1.Designer.cs b/DatabasetoEntityclass/Form1.Designer.cs index bcc6d58..870c2ce 100644 --- a/DatabasetoEntityclass/Form1.Designer.cs +++ b/DatabasetoEntityclass/Form1.Designer.cs @@ -1,4 +1,4 @@ -namespace WindowsFormsApp1 +namespace GenerateClass { partial class Form1 { @@ -108,7 +108,6 @@ this.txt_tablename.Size = new System.Drawing.Size(218, 20); this.txt_tablename.TabIndex = 72; this.txt_tablename.Text = "请选择"; - this.txt_tablename.TextUpdate += new System.EventHandler(this.orderId_TextUpdate); // // textBox1 // diff --git a/DatabasetoEntityclass/Form1.cs b/DatabasetoEntityclass/Form1.cs index 38e7114..4522297 100644 --- a/DatabasetoEntityclass/Form1.cs +++ b/DatabasetoEntityclass/Form1.cs @@ -12,8 +12,11 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using static System.Windows.Forms.VisualStyles.VisualStyleElement; +using GenerateClass.Util; +using System.Xml.Linq; +using JinianNet.JNTemplate; -namespace WindowsFormsApp1 +namespace GenerateClass { public partial class Form1 : Form { @@ -21,98 +24,128 @@ namespace WindowsFormsApp1 { InitializeComponent(); } - string folderName = "GenFolder"; // 文件夹名称 + private void Form1_Load(object sender, EventArgs e) { - this.txt_tablename.Items.AddRange(GetTableName().ToArray()); + this.txt_tablename.Items.AddRange(DbUtil.GetTableName().ToArray()); + this.txt_tablename.TextUpdate += (childSender, childE) => { + string str = this.txt_tablename.Text; //获取输入内容 + List sList = DbUtil.GetTableName(str); //存放数据库查询结果 + //提前下拉,以显示搜索结果(必须要在添加项之前下拉,否则会将第一项自动添加到编辑框内 覆盖掉输入的内容) + this.txt_tablename.DroppedDown = true; //显示下拉列表,但是显示后鼠标指针就不见了 + Cursor.Current = Cursors.Default; //将指针显示出来 + //在表中已录入名字中寻找包含输入内容的项 有则添加到comboBox项中 + this.txt_tablename.Items.Clear(); + this.txt_tablename.Items.AddRange(sList.ToArray()); + this.txt_tablename.Select(this.txt_tablename.Text.Length, 0); + }; + Engine.Configure((options) => { + options.OutMode = OutMode.Auto; + }); } - /// - /// 将数据库字段转换为驼峰命名 - /// - /// - /// - public static string ToCamelCase(string dbField) + private void button1_Click(object sender, EventArgs e) { - string[] words = dbField.Split('_'); - for (int i = 1; i < words.Length; i++) - { - words[i] = char.ToUpper(words[i][0]) + words[i].Substring(1); - } - return string.Join("", words); + fillTemplate(); } - // 根据数据库表名生成实体类名称 - static string GenerateClassName(string tableName) + private void fillTemplate() { - string[] words = tableName.Split('_'); - - StringBuilder sb = new StringBuilder(); - foreach (string word in words) + string tbname = txt_tablename.Text.Trim();//要生成的表名 + string namespaceName = namespace_name.Text.Trim();//名称空间名称 + DataTable dt = null; + if (textBox3.Text.Trim() == "") { - sb.Append(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(word.ToLower())); + dt = DbUtil.GetDbTableInfo(tbname); + } + else + { + dt = DbHelperMySQL.Query(textBox3.Text.Trim()); + } + List> filedInfos = new List>(); + for (int i = 0; i < dt.Rows.Count; i++) + { + var dict = new Dictionary(); + var Name = dt.Rows[i]["Name"].ToString(); + var COMMENT = dt.Rows[i]["COMMENT"].ToString(); + var KeyType = dt.Rows[i]["KeyType"].ToString(); + var Nullable = dt.Rows[i]["Nullable"].ToString(); + Type type = DbUtil.DbTypeStr_To_CsharpType(dt.Rows[i]["Type"].ToString()); + dict["sql_field_name"] = Name; + dict["field_name"] = DbUtil.ToCamelCase(Name); + dict["type_name"] = type.Name; + dict["comment"] = COMMENT; + dict["is_primary_key"] = (String.IsNullOrEmpty(KeyType) ? "false" : "true"); + dict["is_nullable"] = (String.IsNullOrEmpty(KeyType) && !("NULL".Equals(Nullable)) ? "true" : "false"); + filedInfos.Add(dict); + } + using (StreamReader reader = new StreamReader(@".\Template\ModelFile.template")) + { + string fileContent = reader.ReadToEnd(); + var template = Engine.CreateTemplate(fileContent); + template.Set("namespace_name", namespaceName); + template.Set("table_comment", DbUtil.GetTableComment(tbname)); + template.Set("sql_table_name", DbUtil.GenerateClassName(tbname)); + template.Set("table_name", tbname); + template.Set("filedInfos", filedInfos); + template.SetStaticType("string", typeof(string)); + var result = template.Render(); + this.txt_ret.Text = result; + DbUtil.openFile(tbname, result); } - return sb.ToString(); } - - private void button1_Click(object sender, EventArgs e) - { + private void fillStr() { //string constr = txt_constr.Text.Trim();//数据库链接字符串 txt_ret.Text = ""; string tbname = txt_tablename.Text.Trim();//要生成的表名 - if (tbname.Equals("请选择") || tbname.Equals("")) { + if (tbname.Equals("请选择") || tbname.Equals("")) + { MessageBox.Show("请选择表"); - return; + return; }; string namespaceName = namespace_name.Text.Trim(); DataTable dt = null; if (textBox3.Text.Trim() == "") { - dt = GetDbTableInfo(tbname); + dt = DbUtil.GetDbTableInfo(tbname); } else { dt = DbHelperMySQL.Query(textBox3.Text.Trim()); } - var list = new List(); - txt_ret.Text += "using System;\n" + + var infoStr = ""; + infoStr += "using System;\n" + "using NCA_MES_Models.CommonUtils.DB.DBAttribute;\n\n"; - txt_ret.Text += $"namespace {namespaceName} {{\n\n"; - txt_ret.Text += "/// " + "\n" + - $"/// {GetTableComment(tbname)}\n" + - "/// " + "\n" + - $"[TableName(\"{tbname}\")]\n" + - $"public class {GenerateClassName(tbname)}: DBBaseModel<{GenerateClassName(tbname)}>{{"; + infoStr += $"namespace {namespaceName} \n{{\n\n"; + infoStr += "\t/// " + "\n" + + $"\t/// {DbUtil.GetTableComment(tbname)}\n" + + "\t/// " + "\n" + + $"\t[TableName(\"{tbname}\")]\n" + + $"\tpublic class {DbUtil.GenerateClassName(tbname)}: DBBaseModel<{DbUtil.GenerateClassName(tbname)}>\n\t{{"; for (int i = 0; i < dt.Rows.Count; i++) { var Name = dt.Rows[i]["Name"].ToString(); var Type = dt.Rows[i]["Type"].ToString(); var IsNullable = dt.Rows[i]["COMMENT"].ToString(); var KeyType = dt.Rows[i]["KeyType"].ToString(); - Type type = DbTypeStr_To_CsharpType(Type); - txt_ret.Text += "\n\n\t" + "/// " + - "\n\t" + $"///{IsNullable}" + - "\n\t" + "/// " + - (String.IsNullOrEmpty(KeyType)?"":"\n\t[TableId]") + - "\n\t" + $"[TableField(\"{Name}\",\"{IsNullable}\")]" + - "\n\t" + $"public {type.Name} {ToCamelCase(Name)} {{ get; set; }}"; - //加注释记得引用using + var Nullable = dt.Rows[i]["Nullable"].ToString(); + Type type = DbUtil.DbTypeStr_To_CsharpType(Type); + infoStr += "\t\n\n\t" + "/// " + + "\t\n\t" + $"///{IsNullable}" + + "\t\n\t" + "/// " + + (String.IsNullOrEmpty(KeyType) ? "" : "\n\t[TableId]") + + (String.IsNullOrEmpty(KeyType) && !("NULL".Equals(Nullable)) ? "\n\t[NotEmpty]" : "") + + "\t\n\t" + $"[TableField(\"{Name}\",\"{IsNullable}\")]" + + "\t\n\t" + $"public {type.Name} {DbUtil.ToCamelCase(Name)} {{ get; set; }}"; + //加注释记得引用using } - txt_ret.Text += "\n}\n}"; - // 创建文件夹 - string folderPath = Path.Combine(Environment.CurrentDirectory, folderName); - Directory.CreateDirectory(folderPath); - - // 创建文件并写入内容 - string filePath = Path.Combine(folderPath, GenerateClassName(tbname)+".cs"); - File.WriteAllText(filePath, txt_ret.Text); - - // 打开文件夹 - System.Diagnostics.Process.Start(folderPath); + infoStr += "\n\t}"; + infoStr += "\n}"; + this.txt_ret.Text = infoStr; + DbUtil.openFile(tbname, infoStr); } - private void button2_Click(object sender, EventArgs e) { string tbname = txt_tablename.Text.Trim();//要生成的表名 @@ -124,7 +157,7 @@ namespace WindowsFormsApp1 DataTable dt = null; if (textBox3.Text.Trim() == "") { - dt = GetDbTableInfo(tbname); + dt = DbUtil.GetDbTableInfo(tbname); } else { @@ -163,12 +196,11 @@ namespace WindowsFormsApp1 DataTable dt = null; if (textBox3.Text.Trim() == "") { - dt = GetDbTableInfo(tbname); + dt = DbUtil.GetDbTableInfo(tbname); } else { dt = DbHelperMySQL.Query(textBox3.Text.Trim()); } - string uidatagridview = textBox2.Text.Trim(); textBox1.Text = $"this.{uidatagridview}.AutoGenerateColumns = false;"; textBox1.Text += $" string sql = $\"SELECT column_name, column_comment from information_schema.COLUMNS where table_name = '{tbname}' ORDER BY ORDINAL_POSITION; \";\r\n" + @@ -205,8 +237,8 @@ namespace WindowsFormsApp1 textBox1.Text += $" {uidatagridview}.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader;\n"; textBox1.Text += $"DataTable data = DbHelperMySQL.Query(\"select * from {tbname}\");\n"; textBox1.Text += $"this.{uidatagridview}.DataSource = data;\n"; - } + private void button4_Click(object sender, EventArgs e) { string tbname = txt_tablename.Text.Trim();//要生成的表名 @@ -215,30 +247,26 @@ namespace WindowsFormsApp1 MessageBox.Show("请选择表"); return; }; - - - DataTable dt = null; - if (textBox3.Text.Trim() == "") - { - dt = GetDbTableInfo(tbname); - } - else { - dt = DbHelperMySQL.Query(textBox3.Text.Trim()); - } + DataTable dt = null; + if (textBox3.Text.Trim() == "") dt = DbUtil.GetDbTableInfo(tbname); + else dt = DbHelperMySQL.Query(textBox3.Text.Trim()); string uidatagridview = textBox2.Text.Trim(); textBox1.Text = $"this.{uidatagridview}.AutoGenerateColumns = false;"; textBox1.Text += "List cols = new List();\n\n"; + var list = new List(); for (int i = 0; i < dt.Rows.Count; i++) { var Name = dt.Rows[i]["Name"].ToString(); var IsNullable = dt.Rows[i]["COMMENT"].ToString(); + Type type = DbUtil.DbTypeStr_To_CsharpType(dt.Rows[i]["Type"].ToString()); + if(type.Name== "DateTime") list.Add(Name); textBox1.Text += $"DataGridViewTextBoxColumn {Name}Cloumn = new DataGridViewTextBoxColumn();\n"; textBox1.Text += $"{Name}Cloumn.Name = \"{Name}\";" + $"{Name}Cloumn.HeaderText =\"{IsNullable}\";" + $"{Name}Cloumn.DataPropertyName = \"{Name}\";" + $"cols.Add({Name}Cloumn);\n\n"; } - textBox1.Text += "DataGridViewButtonColumn editBtn = new DataGridViewButtonColumn();\r\n" + + /* textBox1.Text += "DataGridViewButtonColumn editBtn = new DataGridViewButtonColumn();\r\n" + "editBtn.HeaderText = \"编辑\";\r\n" + "editBtn.Name = \"editBtn\";\r\n" + "editBtn.Text = \"编辑\";\r\n" + @@ -258,165 +286,37 @@ namespace WindowsFormsApp1 "}\r\n" + $"this.{uidatagridview}.Columns.AddRange(cols.ToArray());\r\n\r\n" + $"if (this.{uidatagridview}.Columns.Count > 0)\r\n" + - $"this.{uidatagridview}.FirstDisplayedScrollingColumnIndex = this.{uidatagridview}.Columns.Count - 2;\n"; + $"this.{uidatagridview}.FirstDisplayedScrollingColumnIndex = this.{uidatagridview}.Columns.Count - 2;\n";*/ textBox1.Text += $" {uidatagridview}.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader;\n"; textBox1.Text += $"DataTable data = DbHelperMySQL.Query(\"select * from {tbname}\");\n"; textBox1.Text += $"this.{uidatagridview}.DataSource = data;\n"; - /* textBox1.Text += $"this.{uidatagridview}.Rows.AddRange(data.AsEnumerable().Select(row => {{\r\n" + - "DataGridViewRow dataGridViewRow = new DataGridViewRow();\r\n " + - "DataGridViewButtonCell addCell = new DataGridViewButtonCell();\r\n" + - "addCell.Value = \"新增\";\r\n " + - "dataGridViewRow.Cells.Add(addCell);\r\n " + - "DataGridViewButtonCell editCell = new DataGridViewButtonCell();\r\n" + - "editCell.Value = \"修改\";\r\n " + - "dataGridViewRow.Cells.Add(editCell);\r\n " + - "foreach (var item in row.ItemArray.Reverse())\r\n " + - "{\r\n" + - "DataGridViewTextBoxCell cell = new DataGridViewTextBoxCell();\r\n" + - "cell.Value = item;\r\n " + - "dataGridViewRow.Cells.Add(cell);\r\n" + - "}\r\n" + - "dataGridViewRow.Height = 40;\r\n" + - "return dataGridViewRow;\r\n" + - "}).ToArray());";*/ - - } - //订单下拉模糊搜索 - private void orderId_TextUpdate(object sender, EventArgs e) //不要用TextChanged - { - string s = this.txt_tablename.Text; //获取输入内容 - List sList = GetTableName(s); //存放数据库查询结果 - //提前下拉,以显示搜索结果(必须要在添加项之前下拉,否则会将第一项自动添加到编辑框内 覆盖掉输入的内容) - this.txt_tablename.DroppedDown = true; //显示下拉列表,但是显示后鼠标指针就不见了 - Cursor.Current = Cursors.Default; //将指针显示出来 - - //在表中已录入名字中寻找包含输入内容的项 有则添加到comboBox项中 - this.txt_tablename.Items.Clear(); - this.txt_tablename.Items.AddRange(sList.ToArray()); - this.txt_tablename.Select(this.txt_tablename.Text.Length, 0); - } - - /// - /// 根据参数,获取数据表信息 - /// - /// - public static DataTable GetDbTableInfo(string tabname) - { - string sql = @"SELECT - c.COLUMN_NAME AS Name, - c.COLUMN_TYPE AS Type, - c.COLUMN_COMMENT AS Comment, - CASE WHEN CONSTRAINT_NAME = 'PRIMARY' THEN 'PRIMARY KEY' ELSE '' END AS KeyType - FROM - INFORMATION_SCHEMA.COLUMNS c - LEFT JOIN - INFORMATION_SCHEMA.KEY_COLUMN_USAGE k - ON - c.TABLE_SCHEMA = k.TABLE_SCHEMA - AND c.TABLE_NAME = k.TABLE_NAME - AND c.COLUMN_NAME = k.COLUMN_NAME - WHERE - c.TABLE_NAME = '{0}' - ORDER BY - c.ORDINAL_POSITION;"; - //string str = $"SELECT COLUMN_NAME AS Name, COLUMN_TYPE AS Type,COLUMN_COMMENT AS COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{tabname}' ORDER BY ORDINAL_POSITION;"; - var dt = DbHelperMySQL.Query(String.Format(sql, tabname)); - return dt; - } - - - public static List GetTableName(string tableName) - { - string sql = $"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{DbHelperMySQL.DbName}' AND TABLE_NAME LIKE '{tableName}%' limit 20;"; - var dt = DbHelperMySQL.Query(sql); - //查询数据库表中所有已录入人员 - List sList = new List(); //存放数据库查询结果 - for (int i = 0; i < dt.Rows.Count; i++) - { - sList.Add(dt.Rows[i]["TABLE_NAME"].ToString()); - } - return sList; - //return dt; - } - public static string GetTableComment(string tableName) - { - string sql = $"SELECT TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{DbHelperMySQL.DbName}' AND TABLE_NAME ='{tableName}';"; - var dt = DbHelperMySQL.Query(sql); - - if(dt.Rows.Count<1) return tableName; - return dt.Rows[0]["TABLE_COMMENT"].ToString(); - } - - public static List GetTableName() - { - string sql = $"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{DbHelperMySQL.DbName}';"; - var dt = DbHelperMySQL.Query(sql); - //查询数据库表中所有已录入人员 - List sList = new List(); //存放数据库查询结果 - for (int i = 0; i < dt.Rows.Count; i++) + if (list.Count > 0) { - sList.Add(dt.Rows[i]["TABLE_NAME"].ToString()); + textBox1.Text += $@" + DateTimePicker dtp = new DateTimePicker(); + convertBeginDgv.Controls.Add(dtp); + dtp.Visible = false; + dtp.TextChanged += (sender, e) => convertBeginDgv.CurrentCell.Value = dtp.Value.ToString(""yyyy-MM-dd""); + dtp.CloseUp += (sender, e) => dtp.Visible = false; + convertBeginDgv.CellClick += (sender, e) => {{ + if (e.ColumnIndex == -1 || e.RowIndex == -1) return; + DataGridView dgv = (sender as DataGridView); + if (new List() {{ + {DbUtil.joinList(list)} + }}.Contains(dgv.Columns[e.ColumnIndex].Name)) + {{ + var _Recatngle = dgv.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); + dtp.Size = _Recatngle.Size; + dtp.Location = _Recatngle.Location; + dtp.Visible = true; + }} + else dtp.Visible = false; + }}; + convertBeginDgv.Scroll += (sender, e) => dtp.Visible = false; + convertBeginDgv.SizeChanged += (sender, e) => {{ if (dtp.Visible) dtp.Visible = false; }};"; } - return sList; - //return dt; - } - /// - /// 类型转换枚举 - /// - protected Dictionary DbTypeDic { get; } = new Dictionary() - { - { "int", typeof(Int32) }, - { "text", typeof(string) }, - { "enum", typeof(string) }, - { "bigint", typeof(Int64) }, - { "binary", typeof(byte[]) }, - { "bit", typeof(bool) }, - { "char", typeof(string) }, - { "date", typeof(DateTime) }, - { "datetime", typeof(DateTime) }, - { "datetime2", typeof(DateTime) }, - { "decimal", typeof(decimal) }, - { "float", typeof(double) }, - { "image", typeof(byte[]) }, - { "money", typeof(decimal) }, - { "nchar", typeof(string) }, - { "ntext", typeof(string) }, - { "numeric", typeof(decimal) }, - { "nvarchar", typeof(string) }, - { "real", typeof(Single) }, - { "smalldatetime", typeof(DateTime) }, - { "smallint", typeof(Int16) }, - { "smallmoney", typeof(decimal) }, - { "timestamp", typeof(DateTime) }, - { "tinyint", typeof(string) }, - { "varbinary", typeof(byte[]) }, - { "varchar", typeof(string) }, - { "variant", typeof(object) }, - { "uniqueidentifier", typeof(Guid) }, - }; - /// - /// 获取字段类型 - /// - /// - /// - public virtual Type DbTypeStr_To_CsharpType(string dbTypeStr) - { - if (dbTypeStr.Contains('(')) - { - string[] strings = dbTypeStr.Split('('); - dbTypeStr = strings[0]; - } - string _dbTypeStr = dbTypeStr.ToLower(); - Type type = null; - if (DbTypeDic.ContainsKey(_dbTypeStr)) - type = DbTypeDic[_dbTypeStr]; - else - type = typeof(string); - - return type; } - } } diff --git a/DatabasetoEntityclass/Program.cs b/DatabasetoEntityclass/Program.cs index 389dad4..da1e228 100644 --- a/DatabasetoEntityclass/Program.cs +++ b/DatabasetoEntityclass/Program.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; -namespace WindowsFormsApp1 +namespace GenerateClass { internal static class Program { diff --git a/DatabasetoEntityclass/Properties/Resources.Designer.cs b/DatabasetoEntityclass/Properties/Resources.Designer.cs index 8b479b7..db55268 100644 --- a/DatabasetoEntityclass/Properties/Resources.Designer.cs +++ b/DatabasetoEntityclass/Properties/Resources.Designer.cs @@ -1,69 +1,61 @@ //------------------------------------------------------------------------------ // // 此代码由工具生成。 -// 运行时版本: 4.0.30319.42000 +// 运行时版本:4.0.30319.42000 // -// 对此文件的更改可能导致不正确的行为,如果 -// 重新生成代码,则所做更改将丢失。 +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 // //------------------------------------------------------------------------------ -namespace WindowsFormsApp1.Properties -{ - - +namespace GenerateClass.Properties { + using System; + + /// - /// 强类型资源类,用于查找本地化字符串等。 + /// 一个强类型的资源类,用于查找本地化的字符串等。 /// // 此类是由 StronglyTypedResourceBuilder // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen // (以 /str 作为命令选项),或重新生成 VS 项目。 - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources - { - + internal class Resources { + private static global::System.Resources.ResourceManager resourceMan; - + private static global::System.Globalization.CultureInfo resourceCulture; - + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() - { + internal Resources() { } - + /// - /// 返回此类使用的缓存 ResourceManager 实例。 + /// 返回此类使用的缓存的 ResourceManager 实例。 /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager - { - get - { - if ((resourceMan == null)) - { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WindowsFormsApp1.Properties.Resources", typeof(Resources).Assembly); + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GenerateClass.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } - + /// /// 重写当前线程的 CurrentUICulture 属性,对 /// 使用此强类型资源类的所有资源查找执行重写。 /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture - { - get - { + internal static global::System.Globalization.CultureInfo Culture { + get { return resourceCulture; } - set - { + set { resourceCulture = value; } } diff --git a/DatabasetoEntityclass/Properties/Settings.Designer.cs b/DatabasetoEntityclass/Properties/Settings.Designer.cs index 438df21..c4cca6f 100644 --- a/DatabasetoEntityclass/Properties/Settings.Designer.cs +++ b/DatabasetoEntityclass/Properties/Settings.Designer.cs @@ -1,28 +1,24 @@ //------------------------------------------------------------------------------ // -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 // -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 // //------------------------------------------------------------------------------ -namespace WindowsFormsApp1.Properties -{ - - +namespace GenerateClass.Properties { + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] - internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase - { - + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.4.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); - - public static Settings Default - { - get - { + + public static Settings Default { + get { return defaultInstance; } } diff --git a/DatabasetoEntityclass/Template/ModelFile.template b/DatabasetoEntityclass/Template/ModelFile.template new file mode 100644 index 0000000..b38d5bb --- /dev/null +++ b/DatabasetoEntityclass/Template/ModelFile.template @@ -0,0 +1,28 @@ +using System; +using NCA_MES_Models.CommonUtils.DB.DBAttribute; + +namespace ${namespace_name} +{ + /// + /// ${table_comment} + /// + [TableName("${sql_table_name}")] + public class ${table_name} : DBBaseModel<${table_name}> + { +$foreach(filedInfo in filedInfos) + + /// + ///${filedInfo["comment"]} + /// +$if(filedInfo["is_primary_key"]=="true") + [TableId] +$end +$if(filedInfo["is_nullable"]=="true") + [NotEmpty] +$end + [TableField("${filedInfo["sql_field_name"]}", "${filedInfo["comment"]}")] + public ${filedInfo["type_name"]} ${filedInfo["field_name"]} { get; set; } +$end + + } +} \ No newline at end of file diff --git a/DatabasetoEntityclass/DbHelper.cs b/DatabasetoEntityclass/Util/DbHelper.cs similarity index 99% rename from DatabasetoEntityclass/DbHelper.cs rename to DatabasetoEntityclass/Util/DbHelper.cs index 11d5207..9408a1a 100644 --- a/DatabasetoEntityclass/DbHelper.cs +++ b/DatabasetoEntityclass/Util/DbHelper.cs @@ -11,7 +11,7 @@ using System.Configuration; using System.Xml; using System.Text.RegularExpressions; -namespace WindowsFormsApp1 +namespace GenerateClass { public class DbHelperMySQL { diff --git a/DatabasetoEntityclass/Util/DbUtil.cs b/DatabasetoEntityclass/Util/DbUtil.cs new file mode 100644 index 0000000..ab13795 --- /dev/null +++ b/DatabasetoEntityclass/Util/DbUtil.cs @@ -0,0 +1,240 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GenerateClass.Util +{ + public class DbUtil + { + public static string folderName = "GenFolder"; // 文件夹名称 + + public static void openFile(string tbname, string infoStr) + { + // 创建文件夹 + string folderPath = Path.Combine(Environment.CurrentDirectory, folderName); + Directory.CreateDirectory(folderPath); + // 创建文件并写入内容 + string filePath = Path.Combine(folderPath, DbUtil.GenerateClassName(tbname) + ".cs"); + File.WriteAllText(filePath, infoStr); + // 打开文件夹 + System.Diagnostics.Process.Start(folderPath); + } + public static string joinList(List list) + { + string str = ""; + foreach (var item in list) + { + str += (str == "" ? "" : ",") + "\"" + item + "\""; + } + return str; + } + /// + /// 根据参数,获取数据表信息 + /// + /// + public static DataTable GetDbTableInfo(string tabname) + { + string sql = @"SELECT + c.COLUMN_NAME AS Name, + c.COLUMN_TYPE AS Type, + c.COLUMN_COMMENT AS Comment, + CASE WHEN CONSTRAINT_NAME = 'PRIMARY' THEN 'PRIMARY KEY' ELSE '' END AS KeyType, + CASE WHEN c.IS_NULLABLE = 'NO' THEN 'NOT NULL' ELSE 'NULL' END AS Nullable + FROM + INFORMATION_SCHEMA.COLUMNS c + LEFT JOIN + INFORMATION_SCHEMA.KEY_COLUMN_USAGE k + ON + c.TABLE_SCHEMA = k.TABLE_SCHEMA + AND c.TABLE_NAME = k.TABLE_NAME + AND c.COLUMN_NAME = k.COLUMN_NAME + WHERE + c.TABLE_NAME = '{0}' + ORDER BY + c.ORDINAL_POSITION;"; + //string str = $"SELECT COLUMN_NAME AS Name, COLUMN_TYPE AS Type,COLUMN_COMMENT AS COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{tabname}' ORDER BY ORDINAL_POSITION;"; + var dt = DbHelperMySQL.Query(String.Format(sql, tabname)); + return dt; + } + + + public static List GetTableName(string tableName) + { + string sql = $"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{DbHelperMySQL.DbName}' AND TABLE_NAME LIKE '{tableName}%' limit 20;"; + var dt = DbHelperMySQL.Query(sql); + //查询数据库表中所有已录入人员 + List sList = new List(); //存放数据库查询结果 + for (int i = 0; i < dt.Rows.Count; i++) + { + sList.Add(dt.Rows[i]["TABLE_NAME"].ToString()); + } + return sList; + //return dt; + } + public static string GetTableComment(string tableName) + { + string sql = $"SELECT TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{DbHelperMySQL.DbName}' AND TABLE_NAME ='{tableName}';"; + var dt = DbHelperMySQL.Query(sql); + + if (dt.Rows.Count < 1) return tableName; + return dt.Rows[0]["TABLE_COMMENT"].ToString(); + } + + public static List GetTableName() + { + string sql = $"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{DbHelperMySQL.DbName}';"; + var dt = DbHelperMySQL.Query(sql); + //查询数据库表中所有已录入人员 + List sList = new List(); //存放数据库查询结果 + for (int i = 0; i < dt.Rows.Count; i++) + { + sList.Add(dt.Rows[i]["TABLE_NAME"].ToString()); + } + return sList; + } + + public static Dictionary DbTypeDic { get; } = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { "int", typeof(int) }, + { "integer", typeof(int) }, + { "tinyint", typeof(byte) }, + { "smallint", typeof(short) }, + { "mediumint", typeof(int) }, + { "bigint", typeof(long) }, + { "float", typeof(float) }, + { "double", typeof(double) }, + { "decimal", typeof(decimal) }, + { "char", typeof(string) }, + { "varchar", typeof(string) }, + { "text", typeof(string) }, + { "mediumtext", typeof(string) }, + { "longtext", typeof(string) }, + { "enum", typeof(string) }, + { "date", typeof(DateTime) }, + { "time", typeof(TimeSpan) }, + { "datetime", typeof(DateTime) }, + { "timestamp", typeof(DateTime) }, + { "year", typeof(int) }, + { "binary", typeof(byte[]) }, + { "varbinary", typeof(byte[]) }, + { "blob", typeof(byte[]) }, + { "mediumblob", typeof(byte[]) }, + { "longblob", typeof(byte[]) }, + { "bit", typeof(bool) }, + { "boolean", typeof(bool) }, + { "json", typeof(string) }, + { "geometry", typeof(object) }, // Geometry 数据类型的映射可能需要特殊处理 + // 更多其他数据类型 + }; + /// + /// 获取字段类型 + /// + /// + /// + public static Type DbTypeStr_To_CsharpType(string dbTypeStr) + { + if (dbTypeStr.Contains('(')) + { + string[] strings = dbTypeStr.Split('('); + dbTypeStr = strings[0]; + } + string _dbTypeStr = dbTypeStr.ToLower(); + Type type = null; + if (DbTypeDic.ContainsKey(_dbTypeStr)) + type = DbTypeDic[_dbTypeStr]; + else + type = typeof(string); + + return type; + } + /// + /// 将数据库字段转换为驼峰命名 + /// + /// + /// + public static string ToCamelCase(string dbField) + { + string[] words = dbField.Split('_'); + for (int i = 1; i < words.Length; i++) + { + words[i] = char.ToUpper(words[i][0]) + words[i].Substring(1); + } + return string.Join("", words); + } + + // 根据数据库表名生成实体类名称 + public static string GenerateClassName(string tableName) + { + string[] words = tableName.Split('_'); + + StringBuilder sb = new StringBuilder(); + foreach (string word in words) + { + sb.Append(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(word.ToLower())); + } + + return sb.ToString(); + } + /* /// + /// 类型转换枚举 + /// + protected Dictionary DbTypeDic { get; } = new Dictionary() + { + { "int", typeof(Int32) }, + { "text", typeof(string) }, + { "enum", typeof(string) }, + { "bigint", typeof(Int64) }, + { "binary", typeof(byte[]) }, + { "bit", typeof(bool) }, + { "char", typeof(string) }, + { "date", typeof(DateTime) }, + { "datetime", typeof(DateTime) }, + { "datetime2", typeof(DateTime) }, + { "decimal", typeof(decimal) }, + { "float", typeof(double) }, + { "image", typeof(byte[]) }, + { "money", typeof(decimal) }, + { "nchar", typeof(string) }, + { "ntext", typeof(string) }, + { "numeric", typeof(decimal) }, + { "nvarchar", typeof(string) }, + { "real", typeof(Single) }, + { "smalldatetime", typeof(DateTime) }, + { "smallint", typeof(Int16) }, + { "smallmoney", typeof(decimal) }, + { "timestamp", typeof(DateTime) }, + { "tinyint", typeof(bool) }, + { "varbinary", typeof(byte[]) }, + { "varchar", typeof(string) }, + { "variant", typeof(object) }, + { "uniqueidentifier", typeof(Guid) }, + }; + /// + /// 获取字段类型 + /// + /// + /// + public virtual Type DbTypeStr_To_CsharpType(string dbTypeStr) + { + if (dbTypeStr.Contains('(')) + { + string[] strings = dbTypeStr.Split('('); + dbTypeStr = strings[0]; + } + string _dbTypeStr = dbTypeStr.ToLower(); + Type type = null; + if (DbTypeDic.ContainsKey(_dbTypeStr)) + type = DbTypeDic[_dbTypeStr]; + else + type = typeof(string); + + return type; + } +*/ + } +} diff --git a/DatabasetoEntityclass/packages.config b/DatabasetoEntityclass/packages.config new file mode 100644 index 0000000..4139890 --- /dev/null +++ b/DatabasetoEntityclass/packages.config @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file