CopyToDataTable无效....生成错误

时间:2011-04-23 16:48:48

标签: c# linq

我从msdn获得了一个示例,代码是:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace LINQTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            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"}};

                        // Load into an existing DataTable, expand the schema and
                        // autogenerate a new Id.
                        DataTable table = new DataTable();
                        DataColumn dc = table.Columns.Add("NewId", typeof(int));
                        dc.AutoIncrement = true;
                        table.Columns.Add("ExtraColumn", typeof(string));

                        var query = from i in items
                                    where i.Price > 9.99
                                    orderby i.Price
                                    select new { i.Price, i.Genre };

                       query.CopyToDataTable(table, LoadOption.PreserveChanges);

                    }
    }

    public class Item
    {
        public int Id { get; set; }
        public double Price { get; set; }
        public string Genre { get; set; }
    }

    public class Book : Item
    {
        public string Author { get; set; }
    }

    public class Movie : Item
    {
        public string Director { get; set; }
    }
}

我收到CopyToDataTable的错误。我错过了什么吗?

1 个答案:

答案 0 :(得分:3)

您必须将对象转换为数据行。

试试这个:

    query.Select(el =>
                     {
                         DataRow row =
                             table.NewRow();
                         row["ExtraColumn"] = el.Genre;
                         return row;
                     }
        ).CopyToDataTable(table, LoadOption.PreserveChanges);