开发者

CopyToDataTable is not working....generate error

I've got a sample from msdn and the code is:

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

I'm getting error for CopyToDataTable. Am I missing something?


You'll have to cast your object to a datarow.

Try this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜