多年前写的一个Access实体类生产工具

偶尔翻到以前写的小玩意,数据表实体类生成!只写了Access数据库,等将来有时间试着看看写一个兼容市面主流数据库的!

代码如下:

 static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }

下面是主窗体代码:

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        #region 全部变量定义
        bool Canmove = false;
        Point Pf;
       // string ConnectionString = "";
        #endregion
        void WriteLog(string logstr)
        {
            textBox2.Text += logstr+"\r\n";
        }
        #region 测试数据库是否能连上
        void TestConnection(string str)
        {
            using (OleDbConnection con = new OleDbConnection(str))
            {
                textBox2.ResetText();
                try
                {
                    WriteLog("尝试打开数据库链接......");
                    con.Open();
                    WriteLog("数据库链接测试成功!");
                }
                catch (Exception ex)
                {
                    WriteLog("数据库链接测试失败:"+ex.Message);
                }
                finally
                {
                    WriteLog("关闭数据库链接....");
                    con.Close();
                }
            }

        }
        #endregion
        #region 取得数据库的表名
        string[] GetTableNames(string str)
        {
            using (OleDbConnection con = new OleDbConnection(str))
            {
                DataTable dt = new DataTable();
               
                    try
                    {
                        con.Open();
                        WriteLog("开始从数据库获得所有表名!");
                        dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "table" });
                        int n = dt.Rows.Count;
                        string[] strTable = new string[n];
                        int m = dt.Columns.IndexOf("TABLE_NAME");
                        for (int i = 0; i < n; i++)
                        {
                            DataRow m_DataRow = dt.Rows[i];
                            strTable[i] = m_DataRow.ItemArray.GetValue(m).ToString();
                        }
                        WriteLog("成功取得所有表名!");
                        return strTable;
                       
                    }
                    catch (Exception ex)
                    {
                        WriteLog("获取表名出错:"+ex.Message);
                        return null;
                    }
                    finally
                    {
                        con.Close();
                        dt.Dispose();
                    }
                }
           
        }
        #endregion
        #region 根据表名取得表中每个字段及对应数据类型
        Dictionary<string ,string > GetCoulmNams(string constr,string TableName)
        {
            using (OleDbConnection con = new OleDbConnection(constr))
            {
                DataTable dt = new DataTable();
                try
                {
                    WriteLog("根据表名称获取所有字段及其对应的数据类型!");
                    con.Open();
                  
                    dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new Object[] { null, null, TableName, null });
                   // dataGridView1.DataSource = dt;
                    int n = dt.Rows.Count;
                    Dictionary<string, string> CoulnmsInfo = new Dictionary<string, string>();
                    int m = dt.Columns.IndexOf("COLUMN_NAME");
                    int j = dt.Columns.IndexOf("DATA_TYPE");
                   
                    for ( int i = 0; i < n; i++)
                    {
                        DataRow m_DataRow = dt.Rows[i];
                        CoulnmsInfo.Add(m_DataRow.ItemArray.GetValue(m).ToString(),GetType((int)m_DataRow.ItemArray.GetValue(j)));
                        WriteLog("获取字段" + m_DataRow.ItemArray.GetValue(m).ToString() + "的类型码成功!");
                    }
                    return CoulnmsInfo;
                }
                catch (Exception ex)
                {
                    WriteLog("获取字段类型出错:"+ex.Message);
                    return null;
                }
                finally
                {
                    con.Close();
                    dt.Dispose();
                }
            }
        }
#endregion
        #region 判断字段是否为主键
        bool IsprimaryKeys(string tbname,string Name)
        {
            OleDbConnection connection = new OleDbConnection(textBox1.Text.Trim());
            connection.Open();
           // DataTable schemaColumns = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new string[] { null, null,tbname, null });
            DataTable primaryKeys = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, new string[] { null, null, tbname });
            connection.Close();
            int j = -1;
            foreach (DataRow row in primaryKeys.Rows)
            {
                string fname=row["COLUMN_NAME"].ToString();
                if (fname  == Name)
                {
                    j++;
                }
                            
             }
            if (j>=0)
            { return true; }
            else
            {
                return false;
            }
           
        }
        #endregion
        #region 数据库类型与C#中类型转换
        string  GetType(int num)
        {
          
            switch (num)
            {
              
                case 2:
                    return "Int16";
                case 3:
                    return "int";
                case 4:
                    return "Single";
                   
                case 5:
                    return "Double";
                case 6:
                case 131:
                    return "decimal";
                case 7:
                    return "DateTime";
                case 11:
                    return "bool";

                case 18:
                    return "byte";
                case 130:
                    return "string";
                case 128:
                    return "Binary";
                case 129:
                    return "char";
                case 0:
                case 8: 
                case 9:
                case 10:
                case 12:
                case 13:
                case 14:
                case 15:
                case 16:
                case 17:
                case 19:
                case 20:
                case 21:
                case 64:
                case 72:
                case 132:
                case 133:
                case 134:
                case 135:
                case 136:
                case 138:
                case 139:
                case 200:
                case 203:
                case 204:
                case 205:
                    return "";

                default: return null ;
                   
                   
            }
         
        }
       #endregion
        #region 写文件
        void WriteFile(string NameSpaces,string FileName1,string FileName2,IDbConnection dbconnect)
        {
            if (File.Exists(FileName1  + ".cs"))
            {
                File.Delete(FileName1 + ".cs");
            }
            if (File.Exists(FileName2 + ".cs"))
            {
                File.Delete(FileName2 + ".cs");
            }
            WriteLog("创建文件!");
            FileInfo f = new FileInfo(FileName1 + ".cs");
            FileInfo f1=new FileInfo (FileName2 + ".cs");
            StreamWriter sw1 = f1.AppendText();
            StreamWriter sw = f.AppendText();
            try
            {
                WriteLog("一.写文件头:");
                WriteLog("1.写DB类文件头!");
                sw1.WriteLine("using System.Data;");
                sw1.WriteLine("using System.Data.Linq;");
                sw1.WriteLine("using System.Data.OleDb;");
                sw1.WriteLine("using System.Diagnostics;");
                sw1.WriteLine("namespace "+NameSpaces );
                sw1.WriteLine("{");
                sw1.WriteLine("public class DB");
                sw1.WriteLine("{");
                sw1.WriteLine("DataContext dc;");
                WriteLog("2.写实体类文件头!");
                sw.WriteLine("using System.Data.Linq.Mapping;");
                sw.WriteLine("namespace\t"+NameSpaces );
                sw.WriteLine ("{");
                //一下根据表生产对应的类,根据表中的字段生产对应属性;
                string[] tables = GetTableNames(textBox1.Text.Trim());
                int l = 1;
                WriteLog("二.写文件内容:");
                foreach (string str in tables)
                {
                    WriteLog("开始写第" + l + "张表("+str+")的实体类!");
                               
                    //根据表明写类名
                    sw.WriteLine("[Table (Name=\""+str+"\")]");
                    sw.WriteLine("public class " + str);
                    sw.WriteLine("{");
                    Dictionary<string, string> di = GetCoulmNams(textBox1.Text, str);
                    foreach (KeyValuePair<string, string> value in di)
                    {
                       

                        WriteLog("开始写字段:" + value.Key );
                        if (IsprimaryKeys(str, value.Key) == true)
                        {
                            sw.WriteLine("[Column(IsPrimaryKey =true)]");
                        }
                        else
                        {
                            sw.WriteLine("[Column]");
                        }
                        sw.WriteLine("public " + value.Value + " " + value.Key + "{get;set;}");
                                         

                    }
                    sw.WriteLine("}");
                    WriteLog("写第" + l + "张表的申明!");
                    sw1.WriteLine("public Table<" + str + ">" + str + ";");
                    l++;      

                }
               

                WriteLog("写DB类的初始化方法!");
                sw1.WriteLine("public DB(IDbConnection con) ");
                sw1.WriteLine("{");
                sw1.WriteLine("dc = new DataContext(con);");
                int n=1;
                foreach(string str in tables)
                {
                    WriteLog("建立第" + n + "张表的Object对象!");
                    sw1.WriteLine(str +"=dc.GetTable<"+str+">();");
                    n++;
                }
                WriteLog("三.写文件尾:");
                sw.WriteLine("}");
                sw1.WriteLine("}");
                sw1.WriteLine("}");
                sw1.WriteLine("}");
                WriteLog("生成文件成功!");
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName = "explorer";
                psi.Arguments = "/e,/select," + Application.StartupPath + FileName1+".cs";
                Process.Start(psi);
              

            }
                catch (Exception ex)
            {
                    WriteLog("生成文件发生错误:"+ex.Message);
             }
            finally
            {
                sw.Close();
                sw1.Close();
            }
        }

        #endregion
        #region 测试链接按钮单击事件
        private void button1_Click(object sender, EventArgs e)
        {
            WriteLog("测试链接按钮单击");
            TestConnection(textBox1.Text.Trim());
        }
        #endregion
        #region 生成.cs文件按钮单击事件
        private void button2_Click(object sender, EventArgs e)
        {
            textBox2.ResetText();
            WriteLog("生成.cs文件按钮单击");
            string namespaces = Interaction.InputBox("请输入命名空间!", "输入命名空间", "gaofajin",Control.MousePosition.X -200,Control.MousePosition.Y-100);
            if (namespaces.Length == 0)
            {
                WriteLog("没有输入命名空间,生成文件操作无法继续!");
                return;
            }
            string filename1 = Interaction.InputBox("请输入实体类文件名称!", "输入文件名", "gaofajinmodel", Control.MousePosition.X-200, Control.MousePosition.Y-100);
            if (namespaces.Length == 0)
            {
                WriteLog("没有输入实体类文件名!生成文件操作无法继续!");
                return;
            }
            string filename2 = Interaction.InputBox("请输入DB类文件名称!", "输入文件名", "gaofajinDB", Control.MousePosition.X -200, Control.MousePosition.Y-100);
            if (namespaces.Length == 0)
            {
                WriteLog("没有输入DB类文件名!生成文件操作无法继续!");
                return;
            }
            IDbConnection c = new OleDbConnection(textBox1.Text.Trim());
            WriteFile(namespaces,filename1,filename2,c);      
          
        }
        #endregion
        #region 退出程序按钮单机时间
        private void button3_Click(object sender, EventArgs e)
        {
            Close();
        }
        #endregion
        #region 使无边框的窗体可以拖动
        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (Canmove == true && e.Button == MouseButtons.Left)
            {
                Point p = Control.MousePosition;
                p.Offset(Pf);
                Location = p;

            }
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            Canmove = false;
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Canmove = true;
                Pf = new Point(-e.X, -e.Y);
            }
        }
        #endregion
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            WriteLog("程序正在被关闭!");
            if (DialogResult.OK != MessageBox.Show("确定退出程序吗?", "退出程序", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
            {
                e.Cancel = true;
            }
            else { e.Cancel = false; }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            textBox1.Text = ShowConnectDialog();
        }
        string ShowConnectDialog()
        {
            string ConnectionString = string.Empty;
            DataConnectionDialog dcd = new DataConnectionDialog();
            dcd.DataSources.Add(DataSource.AccessDataSource);
            dcd.DataSources.Add(DataSource.OdbcDataSource);
            dcd.DataSources.Add(DataSource.OracleDataSource);
            dcd.DataSources.Add(DataSource.SqlDataSource);
            dcd.DataSources.Add(DataSource.SqlFileDataSource);
           
            if (DialogResult.OK ==DataConnectionDialog.Show(dcd))
            {
                ConnectionString = dcd.ConnectionString;
            }
            return ConnectionString;
        }
    }

原文地址:https://www.cnblogs.com/gfjin/p/8093122.html