遇到 LINQ 匿名類型、DataTable 查詢結果、原始 SQL 需對應實體類別時,免手寫屬性,直接用反射/ADO.NET Schema 產生類別字串,貼上即用。
using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Text.RegularExpressions;
public static class ClassGenerating
{
// 統一型別名稱映射 (C# 關鍵字)
private static string TypeName(Type t)
{
if (t == typeof(int)) return "int";
if (t == typeof(string)) return "string";
if (t == typeof(bool)) return "bool";
if (t == typeof(DateTime)) return "DateTime";
if (t == typeof(decimal)) return "decimal";
if (t == typeof(double)) return "double";
if (t == typeof(float)) return "float";
if (t == typeof(long)) return "long";
if (t == typeof(short)) return "short";
if (t == typeof(byte)) return "byte";
if (t == typeof(Guid)) return "Guid";
if (t == typeof(byte[])) return "byte[]";
// Nullable
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
return TypeName(t.GetGenericArguments()[0]) + "?";
return t.Name; // fallback
}
/// 匿名物件 → 類別字串
public static string DynamicToClass(object entity, string className)
{
var sb = new StringBuilder();
var props = entity.GetType().GetProperties();
sb.AppendLine($"public class {className} {{");
foreach (var p in props)
{
string type = TypeName(p.PropertyType);
sb.AppendLine($" public {type} {p.Name} {{ get; set; }}");
}
sb.AppendLine("}");
return sb.ToString();
}
/// DataTable → 類別字串
public static string DataTableToClass(DataTable dt, string className)
{
var sb = new StringBuilder();
sb.AppendLine($"public class {className} {{");
foreach (DataColumn col in dt.Columns)
{
string type = TypeName(col.DataType);
sb.AppendLine($" public {type} {col.ColumnName} {{ get; set; }}");
}
sb.AppendLine("}");
return sb.ToString();
}
/// SQL 查詢 → 類別字串 (需開啟連線)
public static string SqlToClass(string sql, string className,
string server, string database, string uid, string pwd)
{
using (var conn = new SqlConnection($"Server={server};Database={database};User={uid};Password={pwd};"))
using (var cmd = new SqlCommand(sql, conn))
{
conn.Open();
using (var reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))
{
var dt = reader.GetSchemaTable();
return DataTableToClass(dt, className);
}
}
}
}
// 1. 匿名類型
var anon = new { Id = 1, Name = "Tom", Price = 99.9m, Tags = new[] {"A","B"} };
string code1 = ClassGenerating.DynamicToClass(anon, "ProductDto");
// 輸出:
// public class ProductDto {
// public int Id { get; set; }
// public string Name { get; set; }
// public decimal Price { get; set; }
// public string[] Tags { get; set; }
// }
// 2. DataTable
DataTable dt = GetDataTableFromDb();
string code2 = ClassGenerating.DataTableToClass(dt, "OrderDto");
// 3. SQL 查詢
string code3 = ClassGenerating.SqlToClass(
"SELECT Id, Name, Price FROM Products WHERE Active=1",
"ProductDto", ".", "MyDb", "sa", "pwd");
public static void WriteClassToFile(string code, string folder, string className)
{
Directory.CreateDirectory(folder);
string file = Path.Combine(folder, className + ".cs");
File.WriteAllText(file, $@"using System;
using System.Collections.Generic;
namespace MyApp.Models
{{
{code}
}}");
}
public static string DynamicToClass(object entity, string className,
Func filter = null,
Func rename = null)
{
var props = entity.GetType().GetProperties()
.Where(p => filter == null || filter(p));
var sb = new StringBuilder();
sb.AppendLine($"public class {className} {{");
foreach (var p in props)
{
string name = rename?.Invoke(p) ?? p.Name;
string type = TypeName(p.PropertyType);
sb.AppendLine($" public {type} {name} {{ get; set; }}");
}
sb.AppendLine("}");
return sb.ToString();
}
// 使用:排除 Tags,將 Name 改為 ProductName
string code = ClassGenerating.DynamicToClass(anon, "ProductDto",
filter: p => p.Name != "Tags",
rename: p => p.Name == "Name" ? "ProductName" : p.Name);
適用場景: 原型開發、資料庫優先、動態報表、ETL 欄位對應。生產代碼建議配合 T4 模板或 Source Generator 產生編譯期類別,享有 IntelliSense 與型別安全。