zoukankan      html  css  js  c++  java
  • 自己编码实现数据库的映射实体的代码生成器

    以前很多时候都是使用CodeSmith或动软生成相关的数据库访问代码(不喜欢使用持久化框架),可以CodeSmith对中文的支持不好,新下载的6.5的版本,怎样都不能正确显示中文,动软代码生成器的表字段的注释永远都显示不了(李天平的败笔),有几个属性如MySql的smallint,tinyint,得重新更改选项的映射表,太麻烦了。虽然说动软现在提供了模块生成功能,批量生成中对表的重命名也不能够,功能有点弱呀,于是自己写个代码生成器,按自己的规则去生成,注释也出来了,多了注释提示,对开发帮助很大的。代码如下:

            private void CreateModel()
            {
                string connectionString = "server=127.0.0.1;port=3306;User Id=root;Password=root;database=ipbroadcast;Connect Timeout=60;Treat Tiny As Boolean=False";
                MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connectionString);
                conn.Open();
                DataTable table = conn.GetSchema("TABLES");
                foreach (DataRow row in table.Rows)
                {
                    DataTable sheetTable = GetSchemaTable(conn, row);
                    string tName = row["TABLE_NAME"].ToString();
                    CreateEntityFile(conn, tName, sheetTable);
                }
                conn.Close();
            }
    
            private DataTable GetSchemaTable(MySqlConnection conn, DataRow row)
            {
                string sheetName = row["TABLE_Name"].ToString();
                MySqlCommand com = conn.CreateCommand();
                com.CommandType = CommandType.Text;
                com.CommandText = "Select * From " + sheetName;
                IDataReader reader = com.ExecuteReader(CommandBehavior.SchemaOnly);
                DataTable table = reader.GetSchemaTable();
                com.Dispose();
                reader.Close();
                return table;
            }
    
            private void CreateEntityFile(MySqlConnection conn, string tName, DataTable table)
            {
                //定义生成文件的路径
                string tableName = tName;
                string schemaName = "";
                string colName = "";
                string path = @"F:IPBroadcastModelModel1";
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
    
                MySqlCommand com = conn.CreateCommand();
                com.CommandType = CommandType.Text;
                Dictionary<string, string> dict = new Dictionary<string, string>();
                bool isGetComment = false;
    
                //写文件
                string clsName = "Ety" + tableName.Substring(3, 1).ToUpper() + tableName.Substring(4);
                string fileName = clsName + ".cs";
                string fullName = Path.Combine(path, fileName);
    
                using (FileStream fs = new FileStream(fullName, FileMode.Create))
                {
                    StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                    sw.WriteLine("using System;");
                    sw.WriteLine("using System.Text;");
                    sw.WriteLine("using System.Collections.Generic; ");
                    sw.WriteLine("using System.Data;");
                    sw.WriteLine("namespace AEBell.DBManager");
                    sw.WriteLine("{");
                    sw.WriteLine("	[Serializable]");
                    sw.WriteLine("	public class " + clsName);
                    sw.WriteLine("	{");
                    foreach (DataRow row in table.Rows)
                    {
                        //tableName = row["BaseTableName"].ToString();
                        colName = row["ColumnName"].ToString();
                        schemaName = row["BaseSchemaName"].ToString();
                        if (!isGetComment)
                        {
                            isGetComment = true;
                            GetFielComment(tableName, schemaName, com, dict);
                        }
    
                        sw.WriteLine("		/// <summary>");
                        sw.WriteLine("		/// " + dict[colName]);
                        sw.WriteLine("		/// </summary>");
    
                        Type info = row["DataType"] as Type;
                        string declear = info.Name;
                        if (declear.ToUpper() == "SBYTE")   //为了适应动软。
                            declear = "Byte";
                        bool isNull = (bool)row["AllowDBNull"];
                        if (isNull && info.BaseType.Name == "ValueType")
                            declear += "?";
    
                        sw.WriteLine("		public " + declear + " " + colName.Substring(0, 1).ToUpper() + colName.Substring(1));
                        sw.WriteLine("		{");
                        sw.WriteLine("			get;");
                        sw.WriteLine("			set;");
                        sw.WriteLine("		}");
                    }
                    sw.WriteLine("	}");
                    sw.WriteLine("}");
                    sw.Close();
                }
            }
    
            private static void GetFielComment(string tableName, string schemaName, MySqlCommand com, Dictionary<string, string> dict)
            {
                string comment = "";
                com.CommandText = "Select COLUMN_NAME,DATA_TYPE, COLUMN_COMMENT From  INFORMATION_SCHEMA.COLUMNS where table_name ='"
                    + tableName + "' AND table_schema = '" + schemaName + "'"; // AND column_name LIKE '" + colName + "'";
                IDataReader reader = com.ExecuteReader();
                while (reader.Read())
                {
                    string colName = reader.GetString(0);
                    comment = reader.GetString(2);
                    dict[colName] = comment;
                }
    
                reader.Close();
            }
    

     虽然实现不是很严谨,DAL和BLL层也没有实现,但有需要之人是可以很快实现的。不对之处,请指正。

  • 相关阅读:
    02安卓用户界面优化之(三)如何使用菜单
    07-业务敏捷:帮助DevOps快速落地的源动力
    转型之路:企业实施DevOps的常见路径和问题
    价值流分析:关于DevOps转型,我们应该从何处入手
    DevOps的衡量:你是否找到了DevOps的实施路线图
    DevOps的实施:到底是工具先行还是文化先行
    DevOps的价值:数字化转型时代,DevOps是必选项
    DevOps的“定义”:DevOps究竟要解决什么问题
    Jenkins产品经理是如何设计产品的
    关于DevOps组织和文化的那些趣事儿.
  • 原文地址:https://www.cnblogs.com/Yjianyong/p/3334596.html
Copyright © 2011-2022 走看看