Generate class source files (Code generators) and source file code generators for tables in the database.

Source: Internet
Author: User

Generate class source files (Code generators) and source file code generators for tables in the database.

Generate class source files for tables in the database

Using System; using System. collections. generic; using System. data; using System. data. sqlClient; using System. IO; using System. text; namespace ModelCodeGeneratorSample {class Program {static string ConnectionString; static string NamespaceName; static Program () {// load the ConnectionString = "Data Source = 192.168.8.119; Initial Catalog = 22 TopWeb; integrated Security = False; user = EQCCD_HUNTER; password = zhey1bu2012; "; NamespaceName =" Topuc22Top. Model ";} static void Main (string [] args) {var content = GetTableCodeContent (ConnectionString, NamespaceName," TB_Enterprise "); if (! String. IsNullOrWhiteSpace (content) {string descFileFolder = @ "D: \"; if (! Directory. exists (descFileFolder) Directory. createDirectory (descFileFolder); string descFileName = "\ TB_Enterprise.cs"; File. writeAllText (descFileFolder + descFileName, content, System. text. encoding. UTF8) ;}} static string GetTableCodeContent (string conStr, string namespaceName, string tableName, string className = "") // Why not directly use a global parameter less, previous project experience {if (string. isNullOrWhiteSpace (tableName )){ Throw new ArgumentException ("The tableName parameter cannot be Empty, null, or WhiteSpce");} var sb = new StringBuilder (); sb. appendFormat (@ "namespace {0} {public class {1} {", namespaceName ,(! String. IsNullOrWhiteSpace (className )? ClassName: tableName); var dt = GetTableFields (conStr, tableName); foreach (DataRow row in dt. rows) {var columnName = row ["column name"]; var typeString = row ["type"]; var isNullable = row ["empty"]; var description = row ["column description"]; sb. appendFormat (@ "// <summary> // {3} // </summary> public {1} {2} {0} {get; set ;}} ", columnName, typeString, (typeString. toString ()! = "String" & isNullable. ToString () = "yes "? "? ":" "), Description);} sb. appendFormat (@ "}}}", NamespaceName); return sb. toString ();} static DataTable GetTableFields (string conStr, string tableName = "") {var SQL = GetSql (tableName); var dt = ExcuteQuery (conStr, SQL ); return dt;} static string GetSql (string tableName = "") {var SQL = @ "select [Table name] = c. name, [table description] = isnull (f. [value], ''), [column number] =. column_id, [column name] =. name, [column description] = isnull (e. [value], ''), [Database type] = B. name, [type] = case when B. name = 'image' then' byte [] 'when B. name in ('image', 'uniqueidentifier', 'ntext', 'varchar ', 'ntext', 'nchar', 'nvarchar ', 'text', 'Char ') then 'string' when B. name in ('tinyint', 'smallint', 'int', 'bigint') then 'int' when B. name in ('date', 'datetime', 'smalldatetime') then 'datetime' when B. name in ('float', 'decimal', 'numeric ', 'money', 'real', 'smallmoney') then'decimal' When B. name = 'bit' then 'bool 'else B. name end, [identifier] = case when is_identity = 1 then 'is 'else' 'end, [primary key] = case when exists (select 1 from sys. objects x join sys. indexes y on x. type = n' pK' and x. name = y. name join sysindexkeys z on z. ID =. object_id and z. indid = y. index_id and z. colid =. column_id) then' is 'else' end, [number of bytes] = case when. [max_length] =-1 and B. name! = 'Xml' then' max/2G 'when B. name = 'xml' then' 2 ^ 31-1 bytes/2 GB 'else rtrim (. [max_length]) end, [length] = case when ColumnProperty (. object_id,. name, 'precision ') =-1 then' 2 ^ 31-1 'else rtrim (ColumnProperty (. object_id,. name, 'precision ') end, [decimal place] = isnull (ColumnProperty (. object_id,. name, 'Scale'), 0), [empty?] = case when. is_nullable = 1 then' is 'else' end, [default value] = isnull (d. text, '') from sys. columns a left join Sys. types B on. user_type_id = B. user_type_id inner join sys. objects c on. object_id = c. object_id and c. type = 'U' left join syscomments d on. default_object_id = d. ID left join sys. extended_properties e on e. major_id = c. object_id and e. minor_id =. column_id and e. class = 1 left join sys. extended_properties f on f. major_id = c. object_id and f. minor_id = 0 and f. class = 1 where 1 = 1 "; if (! String. isNullOrWhiteSpace (tableName) {SQL + = "and c. name = '"+ tableName +"' ";} SQL + =" order by c. name, is_identity desc,. column_id "; return SQL;} static DataTable ExcuteQuery (string conStr, string plain text, List <SqlParameter> pars = null) {using (SqlConnection conn = new SqlConnection (conStr )) {using (SqlCommand cmd = new SqlCommand (plain text, conn) {if (pars! = Null & pars. count> 0) cmd. parameters. addRange (pars. toArray (); using (SqlDataAdapter adp = new SqlDataAdapter (cmd) {DataTable dt = new DataTable (); adp. fill (dt); return dt ;}}}}}}

Generated. cs File Content

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.