如何将 IQueryable 转换为 DataTable [英] How to convert IQueryable to DataTable

查看:35
本文介绍了如何将 IQueryable 转换为 DataTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 LinQ 编写了查询,并使用了 CopyToDataTable 方法.在该行,它显示了从我的数据库类型到 System.Data.DataRow 的隐式转换类型错误.

I wrote the query using LinQ and I used the CopyToDataTable method. At that line it is showing implicit conversion type error from my database type to System.Data.DataRow.

var query = from i in dbContext.Personaldetails
            where i.ID == 1
            select i;

            return query.CopyToDataTable();

有什么建议吗?

推荐答案

CopyToDataTable 需要 DataRow 对象的集合.请参阅如何:在通用类型 T 不是 DataRow 的情况下实现 CopyToDataTable来解决这个问题.

CopyToDataTable requires collection of DataRow objects. See How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow to solve this problem.

更新:如果您的实体具有可为空字段,您可以修改ObjectShredder.ExtendTable 方法.找到新列添加到表的位置,并删除第二个参数,该参数提供列中的数据类型(DataColumn 类不支持可为空的数据类型):

UPDATE: If your entity has nullable field, you can modify ObjectShredder.ExtendTable method. Find place where new columns are added to table, and remove second parameter, which provides type of data in column (DataColumn class does not support nullable data types):

foreach (PropertyInfo p in type.GetProperties())
{
    if (!_ordinalMap.ContainsKey(p.Name))
    {
        DataColumn dc = table.Columns.Contains(p.Name) ? table.Columns[p.Name]
            // do not provide column type
            : table.Columns.Add(p.Name); 

        _ordinalMap.Add(p.Name, dc.Ordinal);
    }
}

这篇关于如何将 IQueryable 转换为 DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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