2016-03-27 11 views
0

必須從服務器上的mdb文件提取數據。我可以打開並訪問數據。現在我必須將它映射到模型,我不知道如何接收數據作爲模型。我的想法是遍歷接收到的數據DataTabel並將其分配到模型類型的值:OleDb/DataTable到Model

OleDbCommand command = new OleDbCommand(sqlcommand, DbConnection); 
adapter = new OleDbDataAdapter(command); 
builder = new OleDbCommandBuilder(adapter); 
dt = new DataTable(); 
try 
{ 
    DbConnection.Open(); 
    adapter.Fill(dt); 

    foreach (DataRow row in dt.Rows) 
    { 
     var examplemodel= new exampleModel(
     Id = row.ItemArray[0], 
     ... 
    ); 
    } 
} 
catch (Exception ex) 
{ 
} 
finally 
{ 
    DbConnection.Close(); 
} 

這裏的問題是,我不能指定row.ItemArray [X]作爲自排模式的元素.ItemArray [x]是對象類型,我不能將其轉換爲int字符串或其他。 另外我還認爲對於這個問題可能有更簡單更清晰的方法。 任何想法或建議,非常感謝。

回答

1

我更喜歡簡單的Linq。無論使用什麼方法,如果我們使用名稱而不是索引的列,它是非常乾淨和安全的。

你可以做類似的事情。

dt.Rows.AsEnumerable() 
     .Select(r=> new exampleModel() 
       { 
        Id = r.Field<int>("col1"), 
        Name = r.Field<string>("col2"), 
        ... 
       }); 
+0

你好哈日,我喜歡與方法Linq,並感謝你的回答。我嘗試了類似的東西,但是AsEnumerable只是爲整個數據表定義的,而不是爲選定的行定義的。或者我錯過了什麼? – wenzel

+0

'DataTable'沒有'SelectedRows'屬性,你的意思是說基於一些_column_值的過濾器嗎? –

1

您可以使用此

var Entity=(from DataRow dataRow in data.Rows select YourEntity<exampleModel>(dataRow)).ToList(); 

助手類

public static T YourEntity<T>(DataRow row) where T : new() 
      { 
       var entity = new T(); 
       var properties = typeof(T).GetProperties(); 

       foreach (var property in properties) 
       { 
        //Get the description attribute 
        var descriptionAttribute = (DescriptionAttribute)property.GetCustomAttributes(typeof(DescriptionAttribute), true).SingleOrDefault(); 
        if (descriptionAttribute == null) 
         continue; 

        property.SetValue(entity, row[descriptionAttribute.Description]); 
       } 

       return entity; 
      } 

和裝飾實體與適當的數據表頭

public class exampleModel 
{ 
.... 
[Description("Subentity_datatable_header_header")] 
     public string Subentity { get; set; } 
.... 

}