反射小應用之DataTable和ListT互操作

反射小應用之DataTable和List<T>互操作

在程序中,往往會遇到一些小情況,就是數據庫取出來的時候為了方便直接將數據通過存儲在DataSet或DataTable中,這樣做的一個后果是在日后的的對數據進行”細“操作時,就發現它可能沒有List<T>那么方便,而另外一些時候(比如使用SqlBulkCopy的時候)使用DataTable會比較方便。于是我們就會想寫一個專門的它們之間的互操作來使我們在操作它們的時候變得不那么復雜。網上關于它們之間的互操作的解決方法蠻多。這里參考了下它們,結合自己實際應用,寫了一個它們之間互操,代碼如下:

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);//備忘,測試不仔細。});
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)/*必須來在于數據庫來自于文件可能存在問題*/ 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;}} }

?

關乎ToEntities擴展方法的備注:這個方法適合的是DataTable是由數據庫直接返回的情況。如果DataTable數據是由Xml文件直接反序列化而來。就要在初始化DataTable時候,對DaTable的列對應在數據實體中的類型進行指定

關于DataTable數據是直接從文件而來的備注:

public class XmlHelper
{/// <summary> /// 將XML轉換為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 轉換為 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">對象的類型</typeparam>/// <param name="t">序列化對象實例</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對象寫入到指定的IO流文件中try{xmlSerializer.Serialize(writer, t);}catch (Exception){//errr message
        }finally{writer.Close();}}/// <summary>/// Xml反序列化/// </summary>/// <typeparam name="T">對象類型</typeparam>/// <param name="t">對象實例</param>public static List<T> XmlDeserialize<T>(List<T> t, string filePath)  //必須是經過同樣的過程反序列化好的文件
    {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>序列化而來。

做如下調用則會拋出異常(異常處理已經加上,謝謝Mainz)

 var dt = XmlHelper.XmlAnalysisArray(Server.MapPath(@"XML\Students"));var list= dt.ToEntities<Student>();

調試會發現。StudentID在實體中是Int32類型。而反序列化出來的是String類型。關于此處的完美解決方案,希望大家能夠指點。此處美中不足。

代碼下載?

?

posted on 2014-05-25 17:47 深谷&幽蘭 閱讀(...) 評論(...) 編輯 收藏

轉載于:https://www.cnblogs.com/fengchengjushi/p/3751402.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/260403.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/260403.shtml
英文地址,請注明出處:http://en.pswp.cn/news/260403.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python適合什么樣的人群_什么樣的人比較適合選擇Python開發+人工智能技術?

原標題&#xff1a;什么樣的人比較適合選擇Python開發人工智能技術&#xff1f; 互聯網行業最近幾年來確實成為了競相追捧的行業&#xff0c;人工智能、大數據的不斷發展讓Python開發技術成為了繼Java開發之后的又一熱門編程語言。我們都知道&#xff0c;想要學習Python開發編程…

java 8 方法引用(method references)

1 什么是方法引用&#xff08;method references&#xff09;java 8 添加了一個很熟悉但是又很陌生的符號::。 你也許會看到這樣的代碼System.out::println其實就是方法引用&#xff08;method references&#xff09;。由于java 8 把方法/函數也作為第一輸入參數。所以你會看到…

SWT中Button事件的幾種不同寫法

1&#xff0e;匿名內部類寫法button.addSelectionListener(new SelectionAdapter(){Overridepublic void widgetSelected(SelectionEvent e){.....}});釋&#xff1a;當button被單擊時&#xff0c;底層就會檢查button是否注冊了相對就的監聽器&#xff0c;如果有&#xff0c;底…

python中fetchall函數_python中查詢數據庫時fetchone()函數和fetchall()函數的區別

我們在用python操作數據庫的時候,經常會碰見兩個函數:fetchone()和fetchall()剛開始學習的時候可能會搞不清楚他們兩個的區別其實非常簡單首先fetchone()函數它的返回值是單個的元組,也就是一行記錄,如果沒有結果,那就會返回null其次是fetchall()函數,它的返回值是多個元組,即返…

文字對齊格式

text-align:justify; letter-spacing:5px; line-height:40px; text-indent:40px 轉載于:https://www.cnblogs.com/mrcln/p/3757148.html

excel vba 從入門到精通_VBA詞匯-基本元素篇

在公眾號發布學習VBA需要哪些基礎知識這篇文章后&#xff0c;有朋友給我們留言&#xff0c;希望可以出一份VBA基礎的英語知識貼。其實相關的內容我們會在后面所對應知識點一一進行講解&#xff0c;提前劇透其實會少很多學習未知知識的樂趣哦~ 我們會將所涉及的基礎單詞和其說明…

jQuery基礎:remove()與 detach()區別

1、detach&#xff08;&#xff09; detach() 方法移除被選元素&#xff0c;包括所有文本和子節點。這個方法會保留 jQuery 對象中的匹配的元素&#xff0c;因而可以在將來再使用這些匹配的元素。detach() 會保留所有綁定的事件、附加的數據&#xff0c;這一點與 remove() 不同…

python保存模型 特征_Pytorch提取模型特征向量保存至csv的例子

Pytorch提取模型特征向量# -*- coding: utf-8 -*-"""dj"""import torchimport torch.nn as nnimport osfrom torchvision import models, transformsfrom torch.autograd import Variableimport numpy as npfrom PIL import Imageimport torchvi…

Matlab畫圖-非常具體,非常全面

Matlab畫圖 強大的畫圖功能是Matlab的特點之中的一個&#xff0c;Matlab提供了一系列的畫圖函數&#xff0c;用戶不須要過多的考慮畫圖的細節&#xff0c;僅僅須要給出一些基本參數就能得到所需圖形&#xff0c;這類函數稱為高層畫圖函數。此外&#xff0c;Matlab還提供了直接對…

openfeign使用_Feign使用基于配置服務發現

之前寫了篇《Feign在實際項目中的應用實踐總結》Feign在實際項目中的應用實踐總結 - 沐風之境 - 博客園?www.cnblogs.com總結了在一般項目中如何使用Feign這個提升開發效率的利器。最近在看Feign的文檔的時候發現了之前遺漏的一些點&#xff0c;所以寫了這篇文章進行補充。pom…

Oracle按用戶進行統計信息更新

按用戶進行統計信息更新 PL/sqldev工具使用system用戶連接到oracle&#xff0c;打開命令窗口執行以下SQL&#xff0c;用戶名請根據實際情況進行更改&#xff1a; begin dbms_stats.gather_schema_stats( ownname > testuser, estimate_percent > dbms_stats.aut…

個人使命宣言

最近在閱讀《高效人士的7個習慣》&#xff0c;其中提到個人使命宣言&#xff0c;也就是個人的行為憲法&#xff0c;有了這個憲法我們在日常生活和工作中才能有法可循有法可依&#xff0c;才不至于在紛繁的社會中迷失自己。通過思考自我感覺制作個人使命宣言還是非常有用的&…

jq js json 轉字符串_JS中JSON對象和String之間的互轉及處理技巧

json&#xff1a;JavaScript 對象表示法(javascript Object Notation)&#xff0c;其實JSON就是一個javaScript的對象(Object)而已。如有不清楚JSON&#xff0c;可以去w3cschool了解http://www.w3school.com.cn/json/1.在Javascript中新建一個字符串(JSON文本)。 var txt { &q…

php中__autoload()方法詳解

原文地址&#xff1a;http://www.php100.com/html/php/lei/2013/0905/5267.html[導讀] PHP在魔術函數__autoload()方法出現以前&#xff0c;如果你要在一個程序文件中實例化100個對象&#xff0c;那么你必須用include或者require包含進來100個類文件&#xff0c;或者你把這100個…

python讀取sql_從python讀取sql的實例方法

從python讀取sql的方法&#xff1a; 1、利用python內置的open函數讀入sql文件&#xff1b; 2、利用第三方庫pymysql中的connect函數連接mysql服務器&#xff1b; 3、利用第三方庫pandas中的read_sql方法讀取傳入的sql文件即可。 python 直接讀取 sql 文件&#xff0c;達到使用 …

我笨,但我不傻

2019獨角獸企業重金招聘Python工程師標準>>> 威哥說&#xff1a;很多朋友給我留言&#xff0c;在學習的過程中如何堅持下去&#xff0c;關于努力和目標&#xff0c;我想談談自己的理解&#xff0c;有不同見解的地方&#xff0c;歡迎留言跟我探討哈。 if(努力苦逼) r…

GNU make manual 翻譯( 一百零四)

繼續翻譯 4.7 Rules without Recipes or Prerequisites If a rule has no prerequisites or recipe, and the target of the rule is a nonexistent file, then make imagines this target to have been updated whenever its rule is run. This implies that all targets dep…

mysql 數字 除以 一萬_騰訊股票接口、和訊網股票接口、新浪股票接口、雪球股票數據、網易股票數據...

騰訊股票接口&#xff1a;大單數據http://stock.finance.qq.com/sstock/list/view/dadan.php?tjs&csz002451&max80&p1&opt10&o0opt10 11 12 13 分別對應成交額大于等于(100萬 200萬 500萬 1000萬)opt1,2,3,4,5,6,7,8 分別對應成交量大于等于(100手 200手 …

asp.net url傳值,彈窗

一,<a>標簽鏈接式傳值 1&#xff0c; <a href"News_list.aspx?ClassID<%#((DataRowView)Container.DataItem)["ClassID"]%>&Editor<%#((DataRowView)Container.DataItem)["Editor"]%>" >傳值</a> 2, <a&g…

windows下python視頻加速調節_Windows下python+ffmpeg實現批量提取、切割視頻中的音頻...

廢話不說&#xff0c;直接上代碼 #遍歷所有mp4文件名->文件名改為字母形式->fffmpeg批量提取音頻、切割音頻->改回中文名 import os import subprocess current os.getcwd() dirs os.listdir(current) for i in dirs: if os.path.splitext(i)[1] ".mp4":…