反射小应用之DataTable和ListT互操作
在程序中,往往會(huì)遇到一些小情況,就是數(shù)據(jù)庫取出來的時(shí)候?yàn)榱朔奖阒苯訉?shù)據(jù)通過存儲(chǔ)在DataSet或DataTable中,這樣做的一個(gè)后果是在日后的的對(duì)數(shù)據(jù)進(jìn)行”細(xì)“操作時(shí),就發(fā)現(xiàn)它可能沒有List<T>那么方便,而另外一些時(shí)候(比如使用SqlBulkCopy的時(shí)候)使用DataTable會(huì)比較方便。于是我們就會(huì)想寫一個(gè)專門的它們之間的互操作來使我們?cè)诓僮魉鼈兊臅r(shí)候變得不那么復(fù)雜。網(wǎng)上關(guān)于它們之間的互操作的解決方法蠻多。這里參考了下它們,結(jié)合自己實(shí)際應(yīng)用,寫了一個(gè)它們之間互操,代碼如下:
public?static?class DataTableEntityInteroperate{/// <summary>/// List<T> to DataTable/// </summary>/// <typeparam name="T">Entity</typeparam>/// <param name="entities">Entities</param>/// <returns>DataTable</returns>internal static DataTable ToDataTable<T>(this List<T> entities) where T : class,new(){//IsNull returnif (null == entities || entities.Count == 0)return null;//Initial ColumnsDataTable dt = new DataTable();PropertyInfo[] pArray = typeof(T).GetProperties();try{Array.ForEach<PropertyInfo>(pArray, p =>{dt.Columns.Add(p.Name);});entities.ForEach(t =>{
//Initial Rows
DataRow dr=dt.NewRow();int i = 0;Array.ForEach<PropertyInfo>(pArray, p =>{if (dt.Columns.Contains(p.Name))dr[i] = p.GetValue(t); //Assigned to each column });i++;
dt.Rows.Add(dr);//備忘,測(cè)試不仔細(xì)。});return dt;}catch (Exception){throw;}}/// <summary>/// DataTable to Entities/// </summary>/// <typeparam name="T">Entity</typeparam>/// <param name="dt">DataTable</param>/// <returns>List<T</returns>internal static List<T> ToEntities<T>(this DataTable dt)/*必須來在于數(shù)據(jù)庫來自于文件可能存在問題*/ where T : class,new(){//IsNullableif (null == dt || dt.Rows.Count == 0)return null;//Initial EntitiesList<T> entities = new List<T>();try{foreach (DataRow row in dt.Rows){PropertyInfo[] pArray = typeof(T).GetProperties();T entity = new T();Array.ForEach<PropertyInfo>(pArray, p =>{
if(row[p.Name]!=DBNull.Value)p.SetValue(entity, row[p.Name], null);});entities.Add(entity);}return entities;}catch (Exception){throw;}} }
?
關(guān)乎ToEntities擴(kuò)展方法的備注:這個(gè)方法適合的是DataTable是由數(shù)據(jù)庫直接返回的情況。如果DataTable數(shù)據(jù)是由Xml文件直接反序列化而來。就要在初始化DataTable時(shí)候,對(duì)DaTable的列對(duì)應(yīng)在數(shù)據(jù)實(shí)體中的類型進(jìn)行指定。
關(guān)于DataTable數(shù)據(jù)是直接從文件而來的備注:
public class XmlHelper {/// <summary> /// 將XML轉(zhuǎn)換為DATATABLE /// </summary> /// <param name="FileURL"></param> /// <returns></returns> public static DataTable XmlAnalysisArray(string filepath){try{DataSet ds = new DataSet();ds.ReadXml(filepath);return ds.Tables[0];}catch (Exception ex){throw ex;}}/// <summary> /// 將DATASET 轉(zhuǎn)換為 XML/// </summary> /// <param name="FileURL"></param> /// <returns></returns> public static void DatasetConversionXML(DataSet ds, string FileURL){try{ds.WriteXml(FileURL);}catch (Exception ex){throw ex;}}/// <summary>/// Xml序列化/// </summary>/// <typeparam name="T">對(duì)象的類型</typeparam>/// <param name="t">序列化對(duì)象實(shí)例</param>/// <param name="filePath">文件路徑</param>public static void XmlSerializer<T>(List<T> t, string filePath){XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<T>));StreamWriter writer = new StreamWriter(filePath);//將s對(duì)象寫入到指定的IO流文件中try{xmlSerializer.Serialize(writer, t);}catch (Exception){//errr message }finally{writer.Close();}}/// <summary>/// Xml反序列化/// </summary>/// <typeparam name="T">對(duì)象類型</typeparam>/// <param name="t">對(duì)象實(shí)例</param>public static List<T> XmlDeserialize<T>(List<T> t, string filePath) //必須是經(jīng)過同樣的過程反序列化好的文件 {XmlSerializer mySerializer = new XmlSerializer(typeof(List<T>));FileStream myFileStream = null;if (File.Exists(filePath)) //檢查文件是否存在 {try{myFileStream = new FileStream(filePath, FileMode.Open);t = (List<T>)mySerializer.Deserialize(myFileStream);}catch (FileNotFoundException){//File not Found }catch (Exception){//the other error message }finally{myFileStream.Close();}}return t;}}Xml文件是直接從DataTable序列化而成,而不是由List<T>序列化而來。
做如下調(diào)用則會(huì)拋出異常(異常處理已經(jīng)加上,謝謝Mainz)
var dt = XmlHelper.XmlAnalysisArray(Server.MapPath(@"XML\Students"));var list= dt.ToEntities<Student>();調(diào)試會(huì)發(fā)現(xiàn)。StudentID在實(shí)體中是Int32類型。而反序列化出來的是String類型。關(guān)于此處的完美解決方案,希望大家能夠指點(diǎn)。此處美中不足。
代碼下載?
?
posted on 2014-05-25 17:47 深谷&幽蘭 閱讀(...) 評(píng)論(...) 編輯 收藏轉(zhuǎn)載于:https://www.cnblogs.com/fengchengjushi/p/3751402.html
總結(jié)
以上是生活随笔為你收集整理的反射小应用之DataTable和ListT互操作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: usaco 17.Jan 铜组T3
- 下一篇: win7 64位系统HP LaserJe