Convert DbContext to Datatable into the first code entity structure

Hi, I am trying to convert the result of a DbContext to a DataTable . I have a class ie ClientTemplateModel that inherits DbContext . In this class, I have one DbSet object ie public virtual DbSet<imagecomment> ImageComments { get; set; } public virtual DbSet<imagecomment> ImageComments { get; set; } public virtual DbSet<imagecomment> ImageComments { get; set; } . I am using the Code first entity framework .

Here is my request.

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

Here I want to convert result to DataTable . How can i convert this?

+7
c # linq-to-sql datatable entity-framework dbcontext
source share
1 answer

you can use an extension method that converts your generic list to Datatable, you can also use IQueryable / Ienumerable instead of IList, follow the code

  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; } 

if you have not used the extension method before, please view msdn

source: fooobar.com/questions/34403 / ...

Hope this helps !!!

+11
source share

All Articles