你的位置:首页 > ASP.net教程

[ASP.net教程]为数据库中的表 生成类的源文件(代码生成器)


为数据库中的表 生成类的源文件

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()    {      //载入配置      ConnectionString = "Data Source=192.168.8.119;Initial Catalog=22TopWeb;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 = "")      //为什么不直接用全局的 少传一个参数,曾经一个项目 的 经验    {      if (string.IsNullOrWhiteSpace(tableName))      {        throw new ArgumentException("参数tableName不能为Empty、null或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["列名"];        var typeString = row["类型"];        var isNullable = row["是否为空"];        var description = row["列说明"];        sb.AppendFormat(@"    /// <summary>    /// {3}    /// </summary>    public {1}{2} {0} {{ get; set; }}", columnName, typeString, (typeString.ToString() != "string" && isNullable.ToString() == "是" ? "?" : ""), 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   [表名]=c.Name,   [表说明]=isnull(f.[value],''),   [列序号]=a.Column_id,   [列名]=a.Name,   [列说明]=isnull(e.[value],''),   [数据库类型]=b.Name,    [类型]= 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 ,  [标识]= case when is_identity=1 then '是' else '' end,   [主键]= 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=a.Object_id and z.indid=y.index_id and z.Colid=a.Column_id)           then '是' else '' end,     [字节数]=case when a.[max_length]=-1 and b.Name!='";      if (!string.IsNullOrWhiteSpace(tableName))      {        sql += "and c.name = '" + tableName + "'";      }      sql += " order by c.name, is_identity desc, a.Column_id";      return sql;    }    static DataTable ExcuteQuery(string conStr, string cmdText, List<SqlParameter> pars = null)    {      using (SqlConnection conn = new SqlConnection(conStr))      {        using (SqlCommand cmd = new SqlCommand(cmdText, 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;          }        }      }    }  }}

 生成的.cs文件内容