您好,登錄后才能下訂單哦!
本篇文章為大家展示了利用ASP.NET怎么不行個根據匿名類和datatable,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
在開發中可能會遇到這幾種情況:
1、EF或LINQ查詢出來的匿名對象在其它地方調用不方便,又懶的手動建實體類
2、通過datatable反射實體需要先建一個類 ,頭痛
3、通過SQL語句返回的實體也需要先建一個類 ,頭痛
4、如果通過代碼生成器要寫模版,需要安裝或者不想生成一堆不用的類
為了解決上面的不便之處,我封裝了一個實體生成類,可以扔到程序里面任意調用
封裝類:
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; } } }
調用如下:
//通過匿名對象生成實體類 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
上述內容就是利用ASP.NET怎么不行個根據匿名類和datatable,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。