添加模板填充功能

main
forget_the_bright 1 year ago
parent 6c6de70415
commit 806d6d2e9c

@ -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
{
}
}

@ -6,8 +6,8 @@
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{7D7B530A-23A4-4024-B263-A942AA53DCC5}</ProjectGuid> <ProjectGuid>{7D7B530A-23A4-4024-B263-A942AA53DCC5}</ProjectGuid>
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>
<RootNamespace>WindowsFormsApp1</RootNamespace> <RootNamespace>GenerateClass</RootNamespace>
<AssemblyName>WindowsFormsApp1</AssemblyName> <AssemblyName>GenerateClass</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion> <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
@ -39,6 +39,9 @@
<Reference Include="Google.Protobuf, Version=3.21.9.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604, processorArchitecture=MSIL"> <Reference Include="Google.Protobuf, Version=3.21.9.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604, processorArchitecture=MSIL">
<HintPath>..\packages\Google.Protobuf.3.21.9\lib\net45\Google.Protobuf.dll</HintPath> <HintPath>..\packages\Google.Protobuf.3.21.9\lib\net45\Google.Protobuf.dll</HintPath>
</Reference> </Reference>
<Reference Include="JinianNet.JNTemplate, Version=2.3.3.0, Culture=neutral, PublicKeyToken=2b90a65531efdba4, processorArchitecture=MSIL">
<HintPath>..\packages\JinianNet.JNTemplate.2.3.3\lib\net46\JinianNet.JNTemplate.dll</HintPath>
</Reference>
<Reference Include="K4os.Compression.LZ4, Version=1.3.5.0, Culture=neutral, PublicKeyToken=2186fa9121ef231d, processorArchitecture=MSIL"> <Reference Include="K4os.Compression.LZ4, Version=1.3.5.0, Culture=neutral, PublicKeyToken=2186fa9121ef231d, processorArchitecture=MSIL">
<HintPath>..\packages\K4os.Compression.LZ4.1.3.5\lib\net462\K4os.Compression.LZ4.dll</HintPath> <HintPath>..\packages\K4os.Compression.LZ4.1.3.5\lib\net462\K4os.Compression.LZ4.dll</HintPath>
</Reference> </Reference>
@ -86,8 +89,7 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Class1.cs" /> <Compile Include="Util\DbHelper.cs" />
<Compile Include="DbHelper.cs" />
<Compile Include="Form1.cs"> <Compile Include="Form1.cs">
<SubType>Form</SubType> <SubType>Form</SubType>
</Compile> </Compile>
@ -96,6 +98,7 @@
</Compile> </Compile>
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Util\DbUtil.cs" />
<EmbeddedResource Include="Form1.resx"> <EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon> <DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource> </EmbeddedResource>
@ -107,6 +110,7 @@
<Compile Include="Properties\Resources.Designer.cs"> <Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen> <AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon> <DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile> </Compile>
<None Include="packages.config" /> <None Include="packages.config" />
<None Include="Properties\Settings.settings"> <None Include="Properties\Settings.settings">
@ -118,6 +122,9 @@
<DependentUpon>Settings.settings</DependentUpon> <DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput> <DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile> </Compile>
<None Include="Template\ModelFile.template">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="App.config" /> <None Include="App.config" />

@ -1,4 +1,4 @@
namespace WindowsFormsApp1 namespace GenerateClass
{ {
partial class Form1 partial class Form1
{ {
@ -108,7 +108,6 @@
this.txt_tablename.Size = new System.Drawing.Size(218, 20); this.txt_tablename.Size = new System.Drawing.Size(218, 20);
this.txt_tablename.TabIndex = 72; this.txt_tablename.TabIndex = 72;
this.txt_tablename.Text = "请选择"; this.txt_tablename.Text = "请选择";
this.txt_tablename.TextUpdate += new System.EventHandler(this.orderId_TextUpdate);
// //
// textBox1 // textBox1
// //

@ -12,8 +12,11 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement; 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 public partial class Form1 : Form
{ {
@ -21,47 +24,83 @@ namespace WindowsFormsApp1
{ {
InitializeComponent(); InitializeComponent();
} }
string folderName = "GenFolder"; // 文件夹名称
private void Form1_Load(object sender, EventArgs e) 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<string> 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;
});
} }
/// <summary> private void button1_Click(object sender, EventArgs e)
/// 将数据库字段转换为驼峰命名
/// </summary>
/// <param name="dbField"></param>
/// <returns></returns>
public static string ToCamelCase(string dbField)
{ {
string[] words = dbField.Split('_'); fillTemplate();
for (int i = 1; i < words.Length; i++)
{
words[i] = char.ToUpper(words[i][0]) + words[i].Substring(1);
}
return string.Join("", words);
} }
// 根据数据库表名生成实体类名称 private void fillTemplate()
static string GenerateClassName(string tableName)
{ {
string[] words = tableName.Split('_'); string tbname = txt_tablename.Text.Trim();//要生成的表名
string namespaceName = namespace_name.Text.Trim();//名称空间名称
StringBuilder sb = new StringBuilder(); DataTable dt = null;
foreach (string word in words) if (textBox3.Text.Trim() == "")
{ {
sb.Append(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(word.ToLower())); dt = DbUtil.GetDbTableInfo(tbname);
}
else
{
dt = DbHelperMySQL.Query(textBox3.Text.Trim());
}
List<Dictionary<string, string>> filedInfos = new List<Dictionary<string, string>>();
for (int i = 0; i < dt.Rows.Count; i++)
{
var dict = new Dictionary<string, string>();
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 fillStr() {
private void button1_Click(object sender, EventArgs e)
{
//string constr = txt_constr.Text.Trim();//数据库链接字符串 //string constr = txt_constr.Text.Trim();//数据库链接字符串
txt_ret.Text = ""; txt_ret.Text = "";
string tbname = txt_tablename.Text.Trim();//要生成的表名 string tbname = txt_tablename.Text.Trim();//要生成的表名
if (tbname.Equals("请选择") || tbname.Equals("")) { if (tbname.Equals("请选择") || tbname.Equals(""))
{
MessageBox.Show("请选择表"); MessageBox.Show("请选择表");
return; return;
}; };
@ -69,50 +108,44 @@ namespace WindowsFormsApp1
DataTable dt = null; DataTable dt = null;
if (textBox3.Text.Trim() == "") if (textBox3.Text.Trim() == "")
{ {
dt = GetDbTableInfo(tbname); dt = DbUtil.GetDbTableInfo(tbname);
} }
else else
{ {
dt = DbHelperMySQL.Query(textBox3.Text.Trim()); dt = DbHelperMySQL.Query(textBox3.Text.Trim());
} }
var list = new List<string>(); var infoStr = "";
txt_ret.Text += "using System;\n" + infoStr += "using System;\n" +
"using NCA_MES_Models.CommonUtils.DB.DBAttribute;\n\n"; "using NCA_MES_Models.CommonUtils.DB.DBAttribute;\n\n";
txt_ret.Text += $"namespace {namespaceName} {{\n\n"; infoStr += $"namespace {namespaceName} \n{{\n\n";
txt_ret.Text += "/// <summary>" + "\n" + infoStr += "\t/// <summary>" + "\n" +
$"/// {GetTableComment(tbname)}\n" + $"\t/// {DbUtil.GetTableComment(tbname)}\n" +
"/// </summary>" + "\n" + "\t/// </summary>" + "\n" +
$"[TableName(\"{tbname}\")]\n" + $"\t[TableName(\"{tbname}\")]\n" +
$"public class {GenerateClassName(tbname)}: DBBaseModel<{GenerateClassName(tbname)}>{{"; $"\tpublic class {DbUtil.GenerateClassName(tbname)}: DBBaseModel<{DbUtil.GenerateClassName(tbname)}>\n\t{{";
for (int i = 0; i < dt.Rows.Count; i++) for (int i = 0; i < dt.Rows.Count; i++)
{ {
var Name = dt.Rows[i]["Name"].ToString(); var Name = dt.Rows[i]["Name"].ToString();
var Type = dt.Rows[i]["Type"].ToString(); var Type = dt.Rows[i]["Type"].ToString();
var IsNullable = dt.Rows[i]["COMMENT"].ToString(); var IsNullable = dt.Rows[i]["COMMENT"].ToString();
var KeyType = dt.Rows[i]["KeyType"].ToString(); var KeyType = dt.Rows[i]["KeyType"].ToString();
Type type = DbTypeStr_To_CsharpType(Type); var Nullable = dt.Rows[i]["Nullable"].ToString();
txt_ret.Text += "\n\n\t" + "/// <summary>" + Type type = DbUtil.DbTypeStr_To_CsharpType(Type);
"\n\t" + $"///{IsNullable}" + infoStr += "\t\n\n\t" + "/// <summary>" +
"\n\t" + "/// </summary>" + "\t\n\t" + $"///{IsNullable}" +
(String.IsNullOrEmpty(KeyType)?"":"\n\t[TableId]") + "\t\n\t" + "/// </summary>" +
"\n\t" + $"[TableField(\"{Name}\",\"{IsNullable}\")]" + (String.IsNullOrEmpty(KeyType) ? "" : "\n\t[TableId]") +
"\n\t" + $"public {type.Name} {ToCamelCase(Name)} {{ get; set; }}"; (String.IsNullOrEmpty(KeyType) && !("NULL".Equals(Nullable)) ? "\n\t[NotEmpty]" : "") +
//加注释记得引用using "\t\n\t" + $"[TableField(\"{Name}\",\"{IsNullable}\")]" +
"\t\n\t" + $"public {type.Name} {DbUtil.ToCamelCase(Name)} {{ get; set; }}";
//加注释记得引用using
} }
txt_ret.Text += "\n}\n}"; infoStr += "\n\t}";
// 创建文件夹 infoStr += "\n}";
string folderPath = Path.Combine(Environment.CurrentDirectory, folderName); this.txt_ret.Text = infoStr;
Directory.CreateDirectory(folderPath); DbUtil.openFile(tbname, infoStr);
// 创建文件并写入内容
string filePath = Path.Combine(folderPath, GenerateClassName(tbname)+".cs");
File.WriteAllText(filePath, txt_ret.Text);
// 打开文件夹
System.Diagnostics.Process.Start(folderPath);
} }
private void button2_Click(object sender, EventArgs e) private void button2_Click(object sender, EventArgs e)
{ {
string tbname = txt_tablename.Text.Trim();//要生成的表名 string tbname = txt_tablename.Text.Trim();//要生成的表名
@ -124,7 +157,7 @@ namespace WindowsFormsApp1
DataTable dt = null; DataTable dt = null;
if (textBox3.Text.Trim() == "") if (textBox3.Text.Trim() == "")
{ {
dt = GetDbTableInfo(tbname); dt = DbUtil.GetDbTableInfo(tbname);
} }
else else
{ {
@ -163,12 +196,11 @@ namespace WindowsFormsApp1
DataTable dt = null; DataTable dt = null;
if (textBox3.Text.Trim() == "") if (textBox3.Text.Trim() == "")
{ {
dt = GetDbTableInfo(tbname); dt = DbUtil.GetDbTableInfo(tbname);
} }
else { else {
dt = DbHelperMySQL.Query(textBox3.Text.Trim()); dt = DbHelperMySQL.Query(textBox3.Text.Trim());
} }
string uidatagridview = textBox2.Text.Trim(); string uidatagridview = textBox2.Text.Trim();
textBox1.Text = $"this.{uidatagridview}.AutoGenerateColumns = false;"; 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" + 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 += $" {uidatagridview}.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader;\n";
textBox1.Text += $"DataTable data = DbHelperMySQL.Query(\"select * from {tbname}\");\n"; textBox1.Text += $"DataTable data = DbHelperMySQL.Query(\"select * from {tbname}\");\n";
textBox1.Text += $"this.{uidatagridview}.DataSource = data;\n"; textBox1.Text += $"this.{uidatagridview}.DataSource = data;\n";
} }
private void button4_Click(object sender, EventArgs e) private void button4_Click(object sender, EventArgs e)
{ {
string tbname = txt_tablename.Text.Trim();//要生成的表名 string tbname = txt_tablename.Text.Trim();//要生成的表名
@ -215,30 +247,26 @@ namespace WindowsFormsApp1
MessageBox.Show("请选择表"); MessageBox.Show("请选择表");
return; return;
}; };
DataTable dt = null;
if (textBox3.Text.Trim() == "") dt = DbUtil.GetDbTableInfo(tbname);
DataTable dt = null; else dt = DbHelperMySQL.Query(textBox3.Text.Trim());
if (textBox3.Text.Trim() == "")
{
dt = GetDbTableInfo(tbname);
}
else {
dt = DbHelperMySQL.Query(textBox3.Text.Trim());
}
string uidatagridview = textBox2.Text.Trim(); string uidatagridview = textBox2.Text.Trim();
textBox1.Text = $"this.{uidatagridview}.AutoGenerateColumns = false;"; textBox1.Text = $"this.{uidatagridview}.AutoGenerateColumns = false;";
textBox1.Text += "List<DataGridViewColumn> cols = new List<DataGridViewColumn>();\n\n"; textBox1.Text += "List<DataGridViewColumn> cols = new List<DataGridViewColumn>();\n\n";
var list = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++) for (int i = 0; i < dt.Rows.Count; i++)
{ {
var Name = dt.Rows[i]["Name"].ToString(); var Name = dt.Rows[i]["Name"].ToString();
var IsNullable = dt.Rows[i]["COMMENT"].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 += $"DataGridViewTextBoxColumn {Name}Cloumn = new DataGridViewTextBoxColumn();\n";
textBox1.Text += $"{Name}Cloumn.Name = \"{Name}\";" + textBox1.Text += $"{Name}Cloumn.Name = \"{Name}\";" +
$"{Name}Cloumn.HeaderText =\"{IsNullable}\";" + $"{Name}Cloumn.HeaderText =\"{IsNullable}\";" +
$"{Name}Cloumn.DataPropertyName = \"{Name}\";" + $"{Name}Cloumn.DataPropertyName = \"{Name}\";" +
$"cols.Add({Name}Cloumn);\n\n"; $"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.HeaderText = \"编辑\";\r\n" +
"editBtn.Name = \"editBtn\";\r\n" + "editBtn.Name = \"editBtn\";\r\n" +
"editBtn.Text = \"编辑\";\r\n" + "editBtn.Text = \"编辑\";\r\n" +
@ -258,165 +286,37 @@ namespace WindowsFormsApp1
"}\r\n" + "}\r\n" +
$"this.{uidatagridview}.Columns.AddRange(cols.ToArray());\r\n\r\n" + $"this.{uidatagridview}.Columns.AddRange(cols.ToArray());\r\n\r\n" +
$"if (this.{uidatagridview}.Columns.Count > 0)\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 += $" {uidatagridview}.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader;\n";
textBox1.Text += $"DataTable data = DbHelperMySQL.Query(\"select * from {tbname}\");\n"; textBox1.Text += $"DataTable data = DbHelperMySQL.Query(\"select * from {tbname}\");\n";
textBox1.Text += $"this.{uidatagridview}.DataSource = data;\n"; textBox1.Text += $"this.{uidatagridview}.DataSource = data;\n";
/* textBox1.Text += $"this.{uidatagridview}.Rows.AddRange(data.AsEnumerable().Select(row => {{\r\n" + if (list.Count > 0)
"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<string> 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);
}
/// <summary>
/// 根据参数,获取数据表信息
/// </summary>
/// <param name="tabname"></param>
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<string> 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<string> sList = new List<string>(); //存放数据库查询结果
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<string> GetTableName()
{
string sql = $"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{DbHelperMySQL.DbName}';";
var dt = DbHelperMySQL.Query(sql);
//查询数据库表中所有已录入人员
List<string> sList = new List<string>(); //存放数据库查询结果
for (int i = 0; i < dt.Rows.Count; i++)
{ {
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<string>() {{
{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;
}
/// <summary>
/// 类型转换枚举
/// </summary>
protected Dictionary<string, Type> DbTypeDic { get; } = new Dictionary<string, Type>()
{
{ "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) },
};
/// <summary>
/// 获取字段类型
/// </summary>
/// <param name="dbTypeStr"></param>
/// <returns></returns>
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;
} }
} }
} }

@ -4,7 +4,7 @@ using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
namespace WindowsFormsApp1 namespace GenerateClass
{ {
internal static class Program internal static class Program
{ {

@ -1,50 +1,45 @@
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// <auto-generated> // <auto-generated>
// 此代码由工具生成。 // 此代码由工具生成。
// 运行时版本: 4.0.30319.42000 // 运行时版本:4.0.30319.42000
// //
// 对此文件的更改可能导致不正确的行为,如果 // 对此文件的更改可能导致不正确的行为,并且如果
// 重新生成代码,则所做更改将丢失。 // 重新生成代码,这些更改将会丢失。
// </auto-generated> // </auto-generated>
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
namespace WindowsFormsApp1.Properties namespace GenerateClass.Properties {
{ using System;
/// <summary> /// <summary>
/// 强类型资源类,用于查找本地化字符串等。 /// 一个强类型资源类,用于查找本地化字符串等。
/// </summary> /// </summary>
// 此类是由 StronglyTypedResourceBuilder // 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。 // (以 /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.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources internal class Resources {
{
private static global::System.Resources.ResourceManager resourceMan; private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture; private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() internal Resources() {
{
} }
/// <summary> /// <summary>
/// 返回此类使用的缓存 ResourceManager 实例。 /// 返回此类使用的缓存 ResourceManager 实例。
/// </summary> /// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager internal static global::System.Resources.ResourceManager ResourceManager {
{ get {
get if (object.ReferenceEquals(resourceMan, null)) {
{ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GenerateClass.Properties.Resources", typeof(Resources).Assembly);
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WindowsFormsApp1.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp; resourceMan = temp;
} }
return resourceMan; return resourceMan;
@ -56,14 +51,11 @@ namespace WindowsFormsApp1.Properties
/// 使用此强类型资源类的所有资源查找执行重写。 /// 使用此强类型资源类的所有资源查找执行重写。
/// </summary> /// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture internal static global::System.Globalization.CultureInfo Culture {
{ get {
get
{
return resourceCulture; return resourceCulture;
} }
set set {
{
resourceCulture = value; resourceCulture = value;
} }
} }

@ -1,28 +1,24 @@
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// <auto-generated> // <auto-generated>
// 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. // 重新生成代码,这些更改将会丢失。
// </auto-generated> // </auto-generated>
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
namespace WindowsFormsApp1.Properties namespace GenerateClass.Properties {
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.4.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default public static Settings Default {
{ get {
get
{
return defaultInstance; return defaultInstance;
} }
} }

@ -0,0 +1,28 @@
using System;
using NCA_MES_Models.CommonUtils.DB.DBAttribute;
namespace ${namespace_name}
{
/// <summary>
/// ${table_comment}
/// </summary>
[TableName("${sql_table_name}")]
public class ${table_name} : DBBaseModel<${table_name}>
{
$foreach(filedInfo in filedInfos)
/// <summary>
///${filedInfo["comment"]}
/// </summary>
$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
}
}

@ -11,7 +11,7 @@ using System.Configuration;
using System.Xml; using System.Xml;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace WindowsFormsApp1 namespace GenerateClass
{ {
public class DbHelperMySQL public class DbHelperMySQL
{ {

@ -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<string> list)
{
string str = "";
foreach (var item in list)
{
str += (str == "" ? "" : ",") + "\"" + item + "\"";
}
return str;
}
/// <summary>
/// 根据参数,获取数据表信息
/// </summary>
/// <param name="tabname"></param>
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<string> 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<string> sList = new List<string>(); //存放数据库查询结果
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<string> GetTableName()
{
string sql = $"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{DbHelperMySQL.DbName}';";
var dt = DbHelperMySQL.Query(sql);
//查询数据库表中所有已录入人员
List<string> sList = new List<string>(); //存放数据库查询结果
for (int i = 0; i < dt.Rows.Count; i++)
{
sList.Add(dt.Rows[i]["TABLE_NAME"].ToString());
}
return sList;
}
public static Dictionary<string, Type> DbTypeDic { get; } = new Dictionary<string, Type>(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 数据类型的映射可能需要特殊处理
// 更多其他数据类型
};
/// <summary>
/// 获取字段类型
/// </summary>
/// <param name="dbTypeStr"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 将数据库字段转换为驼峰命名
/// </summary>
/// <param name="dbField"></param>
/// <returns></returns>
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();
}
/* /// <summary>
/// 类型转换枚举
/// </summary>
protected Dictionary<string, Type> DbTypeDic { get; } = new Dictionary<string, Type>()
{
{ "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) },
};
/// <summary>
/// 获取字段类型
/// </summary>
/// <param name="dbTypeStr"></param>
/// <returns></returns>
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;
}
*/
}
}

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Google.Protobuf" version="3.21.9" targetFramework="net472" />
<package id="JinianNet.JNTemplate" version="2.3.3" targetFramework="net472" />
<package id="K4os.Compression.LZ4" version="1.3.5" targetFramework="net472" />
<package id="K4os.Compression.LZ4.Streams" version="1.3.5" targetFramework="net472" />
<package id="K4os.Hash.xxHash" version="1.0.8" targetFramework="net472" />
<package id="MySql.Data" version="8.0.33" targetFramework="net472" />
<package id="Portable.BouncyCastle" version="1.9.0" targetFramework="net472" />
<package id="System.Buffers" version="4.5.1" targetFramework="net472" />
<package id="System.IO.Pipelines" version="5.0.2" targetFramework="net472" />
<package id="System.Memory" version="4.5.5" targetFramework="net472" />
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net472" />
<package id="System.Runtime.CompilerServices.Unsafe" version="6.0.0" targetFramework="net472" />
<package id="System.Threading.Tasks.Extensions" version="4.5.4" targetFramework="net472" />
</packages>
Loading…
Cancel
Save