在代码优先实体框架中将 DbContext 转换为数据表 [英] Convert DbContext to Datatable in Code first entity framework

查看:21
本文介绍了在代码优先实体框架中将 DbContext 转换为数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试将 DbContext 结果转换为 DataTable.我有一个 class,即 ClientTemplateModel,它 inherits DbContext.在这个类中,我有一个 DbSet 对象,即public virtual DbSetImageComments { 得到;放;}.我正在使用代码优先实体框架.

Hello I am trying to convert DbContext result to DataTable. I have one class i.e. ClientTemplateModel which inherits DbContext. In this class I have one DbSet object i.e. public virtual DbSet<imagecomment> ImageComments { get; set; }. I am using Code first entity framework.

这是我的查询.

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

这里我想将 result 转换成 DataTable.我该如何转换?

Here I am want convert the result into DataTable. How can I convert this?

推荐答案

你可以使用扩展方法将你的通用列表转换为数据表,你也可以使用 IQueryable/Ienumerable 代替 IList ,按照代码

you can use Extension method that converts your Generic List To Datatable , you can use IQueryable/Ienumerable also 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;
    }

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

if you have not used extension method before please see msdn

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

希望这有帮助!!!

这篇关于在代码优先实体框架中将 DbContext 转换为数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆