2012-06-22 16 views
9

我有一個實體列表,其中包含一些字段作爲其他實體。實體到數據表的列表

例如,

MyEntity 
Int id 
ContactEntity Contact -> contactId, Name etc… 
AddressEntity Address 

所以我有List< MyEntity>需要轉換爲數據表。但是從子實體中我只需要選擇一個字段。

是否有可能或者我有其他的選擇。

UPDATE

當我嘗試CopyToDataTable()作爲ivowiblo描述它給了我下面的錯誤

The type 'AnonymousType#1' cannot be used as type parameter 'T' in the generic type or 
method 'System.Data.DataTableExtensions.CopyToDataTable<T>(System.Collections.Generic.IEnumerable<T>)'. 
There is no implicit reference conversion from 'AnonymousType#1' to 'System.Data.DataRow'. 

回答

14

http://msdn.microsoft.com/en-us/library/bb669096.aspx他們解釋瞭如何實現一個CopyToDataTable()方法,該方法不需要將該類型作爲DataRow來處理,例如實體。

只需創建一個返回所需模式的查詢,並使用CopyToDataTable()方法:

var table = entities.Select(x => new { 
             x.Id, 
             Contact = x.Contact.Name, 
             Address = x.Address.Address 
             }).CopyToDataTable(); 

這種解決方案的唯一的問題是,它使用了反射,它可能會碰到的性能,這取決於你的應用程序的負載。如果你需要避免反射,你需要創建一個方法,明確地從你的實體創建DataTable:

var table = new DataTable(); 

table.Columns.Add("Id", typeof(int)) 
table.Columns.Add("Contact", typeof(string)) 
table.Columns.Add("Address", typeof(string)) 

foreach(var entity in entities) { 
    var row = table.NewRow(); 
    row["Id"] = entity.Id; 
    row["Contact"] = entity.Contact.Name; 
    row["Address"] = entity.Address.Address; 
    table.Rows.Add(row); 
} 
0

試試這個代碼(與CopyToDataTable功能):

var query = .... 
DataTable dataTable = query.CopyToDataTable(); 
+1

是的,我已經看到了** http://msdn.microsoft.com/en-us /library/bb669096.aspx**,問題是我有實體內的子實體,我只需要從這些提取一個字段 –