如何将集合转换为数据表

问题描述

能帮我解决这个问题吗?
而且是我想影响对象类型集合Adhérent到数据表

代码:

BiblioEntities b = new BiblioEntities();
var ad = b.Adhérent.SqlQuery(@"select * from Adhérent ").ToList();
DataTable dt = (DataTable)ad;

错误:

不可能的转换类型'System.Collections.Generic.List<Biblio.Adhérent>'和'System.Data.DataTable'

解决方法

我在实体框架模型中使用了以下扩展名,它将适用于任何类型的集合:

public static System.Data.DataTable ToDataTable<T>(this IEnumerable<T> source)
{
    var table = new System.Data.DataTable(typeof(T).Name);

    var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    foreach (var prop in props)
    {
        table.Columns.Add(prop.Name,Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
    }

    foreach (var item in source)
    {
        var values = new object[props.Length];
        for (var i = 0; i < props.Length; i++)
        {
            values[i] = props[i].GetValue(item,null);
        }

        table.Rows.Add(values);
    }

    return table;
}

并将其应用于示例代码将是这样的:

var dt= new BiblioEntities().Adhérent.SqlQuery(@"select * from Adhérent ").ToDataTable();
,

这是另一种实现方式

    public static class DataTableConverter
    {
        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;
        }
    }

要添加到您的代码中,请执行以下操作:

var dt = DataTableConverter.ToDataTable(ad);

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...