惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

有赞技术团队
有赞技术团队
博客园 - 三生石上(FineUI控件)
月光博客
月光博客
F
Full Disclosure
C
Check Point Blog
雷峰网
雷峰网
WordPress大学
WordPress大学
Vercel News
Vercel News
The GitHub Blog
The GitHub Blog
博客园 - Franky
P
Proofpoint News Feed
Engineering at Meta
Engineering at Meta
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
Martin Fowler
Martin Fowler
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
MyScale Blog
MyScale Blog
M
MIT News - Artificial intelligence
IT之家
IT之家
博客园 - 聂微东
L
LangChain Blog
博客园 - 司徒正美
博客园_首页
云风的 BLOG
云风的 BLOG
L
LINUX DO - 最新话题
Jina AI
Jina AI
Latest news
Latest news
L
LINUX DO - 热门话题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
B
Blog RSS Feed
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
P
Palo Alto Networks Blog
T
Tor Project blog
Microsoft Azure Blog
Microsoft Azure Blog
T
Tenable Blog
爱范儿
爱范儿
T
The Exploit Database - CXSecurity.com
酷 壳 – CoolShell
酷 壳 – CoolShell
V
V2EX
S
Securelist
F
Fortinet All Blogs
AWS News Blog
AWS News Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Security Latest
Security Latest
J
Java Code Geeks
T
Threatpost
The Register - Security
The Register - Security
G
Google Developers Blog
Know Your Adversary
Know Your Adversary
T
Tailwind CSS Blog

博客园 - Lance Yang

批量插入Oracle,遇到CLob字段慢的解决办法 c#,利用WPF的ScaleTransform和TranslateTransform实现图片的缩放效果 自定义控件如何给特殊类型的属性添加默认值 z(转) Oracle 12c心得 Entity Framework Code First (八)迁移 Migrations EF Code First学习笔记 C#判断程序是由Windows服务启动还是用户启动 全方位掌握 NSIS 的操作 NSIS学习笔记(转) C#开源框架(整理) 十大前端开发框架(转) .Net 学习 C# 实现无焦点窗体(转载) C++C#时间转换 C#调用C++导出类(转) Socket异步发送的同步控制 C# P/Invoke中传递数组参数 Digital image processing In C# C#数字图像处理(摘录)
自己编码实现数据库的映射实体的代码生成器
Lance Yang · 2013-09-23 · via 博客园 - Lance Yang

以前很多时候都是使用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:\IPBroadcastModel\Model1";
            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("\t[Serializable]");
                sw.WriteLine("\tpublic class " + clsName);
                sw.WriteLine("\t{");
                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("\t\t/// <summary>");
                    sw.WriteLine("\t\t/// " + dict[colName]);
                    sw.WriteLine("\t\t/// </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("\t\tpublic " + declear + " " + colName.Substring(0, 1).ToUpper() + colName.Substring(1));
                    sw.WriteLine("\t\t{");
                    sw.WriteLine("\t\t\tget;");
                    sw.WriteLine("\t\t\tset;");
                    sw.WriteLine("\t\t}");
                }
                sw.WriteLine("\t}");
                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层也没有实现,但有需要之人是可以很快实现的。不对之处,请指正。