- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using MySql.Data.MySqlClient;
- namespace PocoGenerator
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine(GeneratePoco("test", "t1"));
- Console.ReadLine();
- }
- public static string GeneratePoco(string tableSchema, string tableName)
- {
- string sql = string.Format(@"select case column_key
- when 'pri' then 'Key'
- else ''
- end as 'ColumnKey',
- case data_type
- when 'int' then 'int'
- when 'varchar' then 'string'
- end as 'DataType',
- column_name as 'ColumnName'
- from information_schema.columns
- where table_schema='{0}' and table_name='{1}'", tableSchema, tableName);
- MySqlConnection myConn = new MySqlConnection("server=localhost;userid=root;password=xxxx");
- MySqlCommand myCmd = new MySqlCommand(sql, myConn);
- myConn.Open();
- myCmd.ExecuteNonQuery();
- MySqlDataReader myReader = myCmd.ExecuteReader();
- string result = string.Format("[Table(\\"{0} \\")]\\n", tableName);
- string className = CapitalizeFirstLetter(tableName);
- result += "public class " + className + "\\n{\\n";
- while (myReader.Read())
- {
- string columnKey = myReader["ColumnKey"].ToString();
- string currentRow = "";
- if (string.Equals(columnKey, "Key"))
- {
- currentRow += "\\t[Key]\\n";
- }
- string columnName = myReader["ColumnName"].ToString();
- currentRow += string.Format("\\t[Column(\\"{0}\\")\\n", columnName);
- string columnDataType = myReader["DataType"].ToString();
- currentRow += "\\tpublic " + columnDataType + " " + CapitalizeFirstLetter(columnName) + " { get; set; }\\n\\n";
- result += currentRow;
- }
- result += "}";
- return result;
- }
- public static string CapitalizeFirstLetter(string s)
- {
- if (string.IsNullOrEmpty(s))
- return null;
- var firstLetterInUpper = s.ElementAt(0).ToString().ToUpper();
- if(s.Length==1)
- return firstLetterInUpper;
- return firstLetterInUpper + s.Substring(1);
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/0608201513353.html
来源: http://www.codesnippet.cn/detail/0608201513353.html