2015-01-02 26 views
7

こんにちは、DbContextの結果をDataTableに変換しようとしています。私は1つを持っていますclassClientTemplateModelこれはinheritsDbContextです。このクラスでは、私は1つのDbSetオブジェクト、すなわち public virtual DbSet<imagecomment> ImageComments { get; set; }を持っています。私はコードの最初のエンティティフレームワークを使用しています。DbContextをコード内のDatatableに変換する

ここは私の質問です。

using (ClientTemplateModel context = new ClientTemplateModel(connectionString)) 
{ 
    var result = context.ImageComments.Where(p => p.Dcn == dcn).OrderByDescending(p => p.CommentsDateTime); 
} 

はここで私はDataTableresultを変換します。どのように私はこれを変換できますか?

答えて

11
msdn

を参照してくださいする前に、拡張メソッドを使用していない場合は、あなたがコード

public static DataTable ToDataTable<T>(this IList<T> data) 
    { 
     PropertyDescriptorCollection properties = 
      TypeDescriptor.GetProperties(typeof(T)); 
     DataTable table = new DataTable(); 
     foreach (PropertyDescriptor prop in properties) 
      table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); 
     foreach (T item in data) 
     { 
      DataRow row = table.NewRow(); 
      foreach (PropertyDescriptor prop in properties) 
       row[prop.Name] = prop.GetValue(item) ?? DBNull.Value; 
      table.Rows.Add(row); 
     } 
     return table; 
    } 

に従って、代わりのIListののIQueryable/IEnumerableをを使用することができたDataTableにあなたのジェネリックリストを変換拡張メソッドを使用することができます

出典:https://stackoverflow.com/a/5805044/1018054

希望があります。

+0

ありがとうございます。これをどう呼び出すことができますか? –

+0

私は拡張メソッドを使用しましたが、私の場合はどのようにこのメソッドを呼び出すことができますか? –

+0

静的クラスを作成し、このメソッドを内部に作成してからresult.ToDatatable()を実行すると、msdn refが返されます。これについてさらに詳しく調べてください。 –

関連する問題