linq将数据表绑定到数据库时出错

本文关键字:数据库 出错 绑定 数据表 linq | 更新日期: 2023-09-27 18:19:38

我从msdn中反复复制,但下面的代码给了我错误

    The type 'AnonymousType#1' cannot be used as type parameter 'T' in the generic type or method
'System.Data.DataTableExtensions.CopyToDataTable<T>   (System.Collections.Generic.IEnumerable<T>,
 System.Data.DataTable, System.Data.LoadOption)'.  There is no implicit reference conversion from
 'AnonymousType#1' to 'System.Data.DataRow'.    

我的代码:

Item[] items = new Item[] 
                                {
                                    new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Gustavo Achong"}, 
                                  new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "Jessie Zeng"},
                                  new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Marissa Barnes"},
                                  new Movie{Id = 1, Price = 13.40, Genre = "Action", Director = "Emmanuel Fernandez"}
                                };
            // Create a table with a schema that matches that of the query results.            
            DataTable dt1 = new DataTable();
            dt1.Columns.Add("Price", typeof(int));
            dt1.Columns.Add("Genre", typeof(string));
            var query = from i in items
                        where i.Price > 9.99
                        orderby i.Price
                        select new { i.Price, i.Genre };
            query.CopyToDataTable(dt1, LoadOption.PreserveChanges);

如何让它变得可行?

linq将数据表绑定到数据库时出错

试试这段代码,把它放在一个静态助手类中,这将允许您调用ToDataTable();在项目上。

public static DataTable ToDataTable<T>(this IEnumerable<T> data)
    {
        DataTable dt = new DataTable();
        foreach (var prop in data.First().GetType().GetProperties())
        {
            dt.Columns.Add(prop.Name);
        }
        foreach (T entry in data)
        {
            List<object> newRow = new List<object>();
            foreach (DataColumn dc in dt.Columns)
            {
                var val = entry.GetType().GetProperty(dc.ColumnName).GetValue(entry, null);
                newRow.Add(val);
            }
            dt.Rows.Add(newRow.ToArray());
        }
        return dt;
    }

我收到了世界末日的副本。。。

您是否正在尝试实现Microsoft的ObjectShredder<T>类,该类允许将CopyToDataTable与任何类型一起使用?

然后尝试重命名扩展(例如CopyAnyToDataTable),这可能与仅允许DataRow s的DataTableExtensions.CopyToDataTable扩展方法存在命名冲突。

不久前,我也遇到了这个问题,这里有一个类似的问题:

使用CopyToDataTable与";新{..}";LINQ查询