【问题标题】:How to convert Collections to Datatable如何将集合转换为数据表
【发布时间】:2020-12-02 07:27:03
【问题描述】:

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

代码:

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

错误:

Impossible de convertir le type 'System.Collections.Generic.List<Biblio.Adhérent>' en 'System.Data.DataTable'

【问题讨论】:

  • 请用英文发布您的问题,但是您似乎正在尝试将您的 List 转换为 DataTable,如果是这样,您可以这样做stackoverflow.com/a/42550827/2946329
  • 需要转换器:DataTableConverter.ToDataTable(model.Values)
  • 1) 当你已经有一个强类型列表时,为什么还需要一个 DataTable? 2) 如果你真的想要一个强类型列表,为什么要使用 EF/EF Core?使用 SqlCommand 从结果中获取 IDataReader 并使用 DataTable.Load 加载它。 EF Core 在下面使用 SqlCommand,因此遍历列表然后返回 DataTable 只会浪费时间和资源
  • 你真正想做什么?如果您想要 DataTable,似乎不需要像 EF 这样的 ORM
  • 您需要使用 DataAdapter 来填充 DataTable :docs.microsoft.com/en-us/dotnet/api/…

标签: c# sql sql-server entity-framework entity-framework-6


【解决方案1】:

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

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();

【讨论】:

    【解决方案2】:

    这是另一个实现

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

    【讨论】:

      猜你喜欢
      • 2012-02-17
      • 1970-01-01
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 2013-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多