在Code第一实体框架中将DbContext转换为Datatable

Aja*_*y P 7 c# datatable entity-framework linq-to-sql dbcontext

您好我正在尝试将DbContext结果转换为DataTable.我有一个classClientTemplateModel哪个inherits DbContext.在这个课程中我有一个DbSet对象即 public virtual DbSet<imagecomment> ImageComments { get; set; }.我正在使用Code第一个实体框架.

这是我的查询.

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

在这里,我想转换resultDataTable.我该怎么转换呢?

Vis*_*rma 13

你可以使用将你的Generic List转换为Datatable的Extension方法,也可以使用IQueryable/Ienumerable而不是IList,按照代码

  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;
    }
Run Code Online (Sandbox Code Playgroud)

如果您之前没有使用过扩展方法,请参阅msdn

来源:https://stackoverflow.com/a/5805044/1018054

希望这可以帮助 !!!