這篇文章主要介紹了ASP.NET中實現根據匿名類、datatable、sql生成實體類,這個小小工具類非常實用,使用起來也很方便,需要的朋友可以參考下
在開發中可能會遇到這幾種情況:
1、EF或LINQ查詢出來的匿名對象在其它地方調用不方便,又懶的手動建實體類
2、通過datatable反射實體需要先建一個類 ,頭痛
3、通過SQL語句返回的實體也需要先建一個類 ,頭痛
4、如果通過代碼生成器要寫模版,需要安裝或者不想生成一堆不用的類
為了解決上面的不便之處,我封裝了一個實體生成類,可以扔到程序裡面任意調用
封裝類:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using System.Text.RegularExpressions; namespace SyntacticSugar { /// <summary> /// ** 描述:實體生成類 /// ** 創始時間:2015-4-17 /// ** 修改時間:- /// ** 作者:sunkaixuan /// ** qq:610262374 歡迎交流,共同提高 ,命名語法等寫的不好的地方歡迎大家的給出寶貴建議 /// </summary> public class ClassGenerating { /// <summary> /// 根據匿名類獲取實體類的字符串 /// </summary> /// <param name="entity">匿名對象</param> /// <param name="className">生成的類名</param> /// <returns></returns> public static string DynamicToClass(object entity, string className) { StringBuilder reval = new StringBuilder(); StringBuilder propertiesValue = new StringBuilder(); var propertiesObj = entity.GetType().GetProperties(); string replaceGuid = Guid.NewGuid().ToString(); string nullable = string.Empty; foreach (var r in propertiesObj) { var type = r.PropertyType; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { type = type.GetGenericArguments()[0]; nullable = "?"; } if (!type.Namespace.Contains("System.Collections.Generic")) { propertiesValue.AppendLine(); string typeName = ChangeType(type); propertiesValue.AppendFormat("public {0}{3} {1} {2}", typeName, r.Name, "{get;set;}", nullable); propertiesValue.AppendLine(); } } reval.AppendFormat(@" public class {0}{{ {1} }} ", className, propertiesValue); return reval.ToString(); } /// <summary> /// 根據DataTable獲取實體類的字符串 /// </summary> /// <param name="sql"></param> /// <param name="className"></param> /// <returns></returns> public static string DataTableToClass(DataTable dt, string className) { StringBuilder reval = new StringBuilder(); StringBuilder propertiesValue = new StringBuilder(); string replaceGuid = Guid.NewGuid().ToString(); foreach (DataColumn r in dt.Columns) { propertiesValue.AppendLine(); string typeName = ChangeType(r.DataType); propertiesValue.AppendFormat("public {0} {1} {2}", typeName, r.ColumnName, "{get;set;}"); propertiesValue.AppendLine(); } reval.AppendFormat(@" public class {0}{{ {1} }} ", className, propertiesValue); return reval.ToString(); } /// <summary> /// 根據SQL語句獲取實體類的字符串 /// </summary> /// <param name="sql">SQL語句</param> /// <param name="className">生成的類名</param> /// <param name="server">服務名</param> /// <param name="database">數據庫名稱</param> /// <param name="uid">賬號</param> /// <param name="pwd">密碼</param> /// <returns></returns> public static string SqlToClass(string sql, string className, string server, string database, string uid, string pwd) { using (SqlConnection conn = new SqlConnection(string.Format("server={0};uid={2};pwd={3};database={1}", server, database, uid, pwd))) { SqlCommand command = new SqlCommand(); command.Connection = conn; command.CommandText = sql; DataTable dt = new DataTable(); SqlDataAdapter sad = new SqlDataAdapter(command); sad.Fill(dt); var reval = DataTableToClass(dt, className); return reval; } } /// <summary> /// 根據SQL語句獲取實體類的字符串 /// </summary> /// <param name="sql">SQL語句</param> /// <param name="className">生成的類名</param> /// <param name="connName">webconfig的connectionStrings name</param> /// <returns></returns> public static string SqlToClass(string sql, string className, string connName) { string connstr = System.Configuration.ConfigurationManager.ConnectionStrings[connName].ToString(); if (connstr.Contains("metadata"))//ef connstr = Regex.Match(connstr, @"connection string=""(.+)""").Groups[1].Value; using (SqlConnection conn = new SqlConnection(connstr)) { SqlCommand command = new SqlCommand(); command.Connection = conn; command.CommandText = sql; DataTable dt = new DataTable(); SqlDataAdapter sad = new SqlDataAdapter(command); sad.Fill(dt); var reval = DataTableToClass(dt, className); return reval; } } /// <summary> /// 匹配類型 /// </summary> /// <param name="type"></param> /// <returns></returns> private static string ChangeType(Type type) { string typeName = type.Name; switch (typeName) { case "Int32": typeName = "int"; break; case "String": typeName = "string"; break; } return typeName; } } }調用如下:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 //通過匿名對象生成實體類 var dynamicObj = new { id = 1, name = "小名", entity = new enityt1() }; //注意:只能是單個實體不能傳入 List<T> ,集合需要 List[0] string classCode = ClassGenerating.DynamicToClass(dynamicObj, "classDynamic"); //通過datatable生成實體類 DataTable dt = new DataTable(); dt.Columns.Add("Id", typeof(int)); dt.Columns.Add("Name"); classCode = ClassGenerating.DataTableToClass(dt, "classTatabale"); //通過sql語句生成實體類 classCode = ClassGenerating.SqlToClass("select * from note", "Note", "127.0.0.1", "MyWork", "sa", "sasa"); classCode = ClassGenerating.SqlToClass("select * from dbo.AccessoriesDetail", "AccessoriesDetail", "NFDEntities");//通過 config connstring名稱然後在調試狀態把你需要的結果CTRL+C 然後去新建一個類CTRL+V