2011-04-23 70 views
-1

我有從MSDN樣本和代碼是:CopyToDataTable不工作....產生錯誤

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。我錯過了什麼嗎?

+2

什麼類型的錯誤你好嗎? – rsbarro 2011-04-23 17:22:57

+1

你已經問了263個關於SO的問題,你仍然會發布a)只是一段代碼b)沒有正確的格式c)沒有錯誤的細節? – 2011-04-23 18:18:25

+0

試了一下,因爲我可以學到一些東西。但是給我們提供的錯誤會讓事情變得很輕鬆。 – Carra 2011-04-23 18:26:27

回答

3

您必須將您的對象投射到數據行。

試試這個:

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