為數據庫中的表 生成類的源文件
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!='xml' then 'max/2G' when b.Name='xml' then '2^31-1字節/2G' else rtrim(a.[max_length]) end, [長度]=case when ColumnProperty(a.object_id,a.Name,'Precision')=-1 then '2^31-1' else rtrim(ColumnProperty(a.object_id,a.Name,'Precision')) end, [小數位]=isnull(ColumnProperty(a.object_id,a.Name,'Scale'),0), [是否為空]=case when a.is_nullable=1 then '是' else '' end, [默認值]=isnull(d.text,'') from sys.columns a left join sys.types b on a.user_type_id=b.user_type_id inner join sys.objects c on a.object_id=c.object_id and c.Type='U' left join syscomments d on a.default_object_id=d.ID left join sys.extended_properties e on e.major_id=c.object_id and e.minor_id=a.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, 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文件內容