C#根据数据库表生成对应的实体类

我们的知道C#编程是一种面向对象的编程语言。在这个过程中我们往往需要根据数据库表的字段创建对应的实体类对象。手动一个个添加实体类的class文件是一件极为痛苦的事情。数据库少的情况下。我们手动还可以勉强添加。但是一旦一个系统的数据表几百个。手动添加那将是极为痛苦的。所我结合工作的需要使用C#+winform开发了一个基于SQL Server数据的实体类生成工具。

无边框界面设计

数据库查询代码实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace ModelsCreate
{
    public class DbHelper
    {
        //数据库连接字符串
        private string connectStr = "";

        /// <summary>
        /// 构造方法初始化数据库连接字符串
        /// </summary>
        /// <param name="dbAddress"></param>
        /// <param name="dbName"></param>
        /// <param name="account"></param>
        /// <param name="pwd"></param>
        public DbHelper(string dbAddress,string dbName,string account,string pwd) 
        {
            connectStr = $"Server={dbAddress};DataBase={dbName};Uid={account};Pwd={pwd}";
        }

        /// <summary>
        /// 查询数据库中所有表的名称,存放放List集合中
        /// </summary>
        /// <returns></returns>
        public List<string>GetTablesName()
        {
            List<string> tableNames = new List<string>();
            SqlConnection connect = new SqlConnection(connectStr);
            SqlCommand command = new SqlCommand("select name from sys.tables where type ='U' order by name asc",connect);
            try
            {
                connect.Open();
                SqlDataReader sqlDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
                while(sqlDataReader.Read())
                {
                    tableNames.Add(sqlDataReader["name"].ToString());
                }
                sqlDataReader.Close();
                return tableNames;
            }
            catch (Exception ex)
            {
                if(connect!=null)
                {
                    connect.Close();
                }
                throw ex;
            }
        }

        /// <summary>
        /// 更数据表的名称。循环查询每张数据表的字段信息,存到dictionary字典中。数据表名称作为key,数据列名称List集合作为value
        /// </summary>
        /// <param name="tableNames"></param>
        /// <returns></returns>
        public Dictionary<string, List<string>> GetModelsInfo(List<string> tableNames)
        {
            Dictionary<string, List<string>> modelsInfo = new Dictionary<string, List<string>>();
            SqlConnection connect = new SqlConnection(connectStr);
            SqlCommand command = new SqlCommand();
            SqlDataAdapter sda = new SqlDataAdapter(command);
            try
            {
                connect.Open();
                foreach (string tableName in tableNames)
                {
                    command.CommandText = $"select * from {tableName} where 1=0";
                    command.Connection = connect;
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    List<string> clos = new List<string>();
                    for(int index=0;index<dt.Columns.Count;index++)
                    {
                        string closType = dt.Columns[index].DataType.Name;
                        clos.Add($"{dt.Columns[index].ColumnName},{closType}");
                    }
                    modelsInfo.Add(tableName, clos);
                }
                connect.Close();
                return modelsInfo;
            }
            catch (Exception ex)
            {
                if (connect != null)
                {
                    connect.Close();
                }
                throw ex;
            }
            finally
            {
                if (connect != null)
                {
                    connect.Close();
                }
            }
        }
    }
}

cs实体类文件创建代码实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml.Linq;

namespace ModelsCreate
{
    public class Commons
    {
        /// <summary>
        /// cs实体类文件创建
        /// </summary>
        /// <param name="savePath"></param>
        /// <param name="nameSpace"></param>
        /// <param name="modelsInfo"></param>
        public void CreateModels(string savePath, string nameSpace, Dictionary<string, List<string>> modelsInfo)
        {
            foreach (string keys in modelsInfo.Keys)
            {
                //拼接cs实体类文件的中的字符串类容
                StringBuilder columnsName = new StringBuilder();
                StringBuilder classContent = new StringBuilder();
                classContent.Append($"using System;\r\n");
                classContent.Append($"using System.Collections.Generic;\r\n");
                classContent.Append($"using System.Linq;\r\n");
                classContent.Append($"using System.Text;\r\n");
                classContent.Append($"using System.Threading.Tasks;\r\n");
                classContent.Append($"namespace {nameSpace}\r\n");
                classContent.Append("{\r\n");
                classContent.Append($"    public class {keys}\r\n");
                classContent.Append("    {\r\n");
                foreach(string clos in modelsInfo[keys])
                {
                    string[] closTemp= clos.Split(',');
                    columnsName.Append(closTemp[0]+",");
                    classContent.Append("        public "+ ConvertType(closTemp[1])+ " "+ closTemp[0] + " { get; set; }\r\n");
                }
                classContent.Append("    }\r\n");
                classContent.Append($"    //{columnsName}\r\n");
                classContent.Append("}");
                
                this.WriteContent($"{savePath}\\{keys}.cs",classContent.ToString());//每个实体类字符串个类容拼接结束,调用写入方法创建cs实体类文件。并将字符串内容写入cs文件中
            }
        }
        public void WriteContent(string savePath, string content)
        {
            if(File.Exists(savePath))
            {
                File.Delete(savePath);
            }
            FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(content);
            sw.Close();
            fs.Close();
        }

        /// <summary>
        /// 数据类型装换,因为查询的数据表列的数据类型在映射到DataTable时类型有所改变
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        public string ConvertType(string typeName)
        {
            switch (typeName)
            {
                case "Int32":
                    return "int";
                case "Int64":
                    return "long";
                case "Int16":
                    return "short";
                case "Byte":
                    return "byte";
                case "Boolean":
                    return "bool";
                case "Decimal":
                    return "decimal";
                case "Double":
                    return "double";
                case "Single":
                    return "float";
                case "String":
                    return "string";
                case "Byte[]":
                    return "byte[]";
                default:
                    return typeName;
            }
        }
    }
}

UI界面代码实现

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ModelsCreate
{
    public partial class ModelsCreateFrm : Form
    {
        public ModelsCreateFrm()
        {
            InitializeComponent();
        }

        //关闭按钮点击事件
        private void lblClose_Click(object sender, EventArgs e)
        {
            this.Close();//关闭窗体
        }
        //最小化按钮点击事件
        private void lblMiniTask_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;//最小化任务栏
        }
        //最小化鼠标进入事件
        private void lblMiniTask_MouseEnter(object sender, EventArgs e)
        {
            //带鼠标移动到按钮上改变背景色字体颜色
            this.lblMiniTask.BackColor = Color.Red;
            this.lblMiniTask.ForeColor = Color.White;
        }
        //最小化鼠标离开事件
        private void lblMiniTask_MouseLeave(object sender, EventArgs e)
        {
            //带鼠标离开按钮上改变背景色字体颜色
            this.lblMiniTask.BackColor = Color.FromArgb(240, 240, 240);
            this.lblMiniTask.ForeColor = Color.Black;
        }
        //关闭按钮鼠标进入事件
        private void lblClose_MouseEnter(object sender, EventArgs e)
        {
            //带鼠标移动到按钮上改变背景色字体颜色
            this.lblClose.BackColor = Color.Red;
            this.lblClose.ForeColor = Color.White;
        }
        //关闭按钮鼠标离开事件
        private void lblClose_MouseLeave(object sender, EventArgs e)
        {
            //带鼠标离开按钮上改变背景色字体颜色
            this.lblClose.BackColor = Color.FromArgb(240, 240, 240);
            this.lblClose.ForeColor = Color.Black;
        }

        #region 无边框窗体鼠标是无法拖动的。此方法为鼠标拖动窗体的事件
        private bool isMouseDown = false;
        private Point FrmLocation;     //form的location
        private Point mouseOffset;      //鼠标的按下位置
        private void ModelsCreateFrm_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMouseDown = true;
                FrmLocation = this.Location;
                mouseOffset = Control.MousePosition;
            }
        }
        private void ModelsCreateFrm_MouseMove(object sender, MouseEventArgs e)
        {
            int x = 0;
            int y = 0;
            if (isMouseDown)
            {
                Point pt = Control.MousePosition;
                x = mouseOffset.X - pt.X;
                y = mouseOffset.Y - pt.Y;
                this.Location = new Point(FrmLocation.X - x, FrmLocation.Y - y);
            }
        }
        private void ModelsCreateFrm_MouseUp(object sender, MouseEventArgs e)
        {
            isMouseDown = false;
        }
        #endregion

        private List<string> tableNames = null;//声明一个存放数据表名称的集合
        private DbHelper dbHelper = null;//数据库访问类

        //数据连接按钮点击事件
        private void btnConnection_Click(object sender, EventArgs e)
        {
            dbHelper = new DbHelper(this.txtDbAddress.Text, this.txtDbName.Text, this.txtDbAccount.Text, this.txtDbPwd.Text);
            tableNames = dbHelper.GetTablesName();//调用DbHelper中的查询数据库表名称的方法
            this.cboxTableName.DataSource = tableNames;
            this.cboxTableName.SelectedIndex = -1;
        }

        //开始生成cs文件按钮点击事件
        private void btnStartCreate_Click(object sender, EventArgs e)
        {
            try
            {
                Commons commons = new Commons();//创建创建cs实体类文件的对象
                Dictionary<string, List<string>> modelsInfo = dbHelper.GetModelsInfo(tableNames);//调用DbHelper中的查询数据库表列名称的方法
                if (this.cboxTableName.Text.Length == 0)//判断是创建单个数据表的实体类文件,还是创建所有数据表的实体类文件
                {
                    commons.CreateModels(this.txtSavePath.Text, this.txtNamespace.Text, modelsInfo);//调用commons中cs实体类文件创建方法
                }
                else
                {
                    Dictionary<string, List<string>> modelsInfoTemp = new Dictionary<string, List<string>>();
                    modelsInfoTemp.Add(this.cboxTableName.Text,modelsInfo[this.cboxTableName.Text]);
                    commons.CreateModels(this.txtSavePath.Text, this.txtNamespace.Text, modelsInfoTemp);
                }
                MessageBox.Show("实体类文件生成成功", "提示信息");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"程序执行出现异常,具体信息:{ex.Message}", "提示信息");
            }
        }

        //cs文件存放目录选择事件
        private void lblSelectPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog openFile = new FolderBrowserDialog();//打开目录选择窗口选择目录
            openFile.ShowDialog();
            this.txtSavePath.Text = openFile.SelectedPath;//将选择的目录完整路近复制个textBox
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值