0

您好我正在尝试学习 LINQ TO SQL 并尝试使用 POCO 方法映射数据,但我似乎遇到了错误。这是我使用 NORTHWIND 数据库客户表的代码:

   //Customers class
    public class Customers
    {
        public int ID { get;set; }
        public string CompanyName { get;set; }
        public string ContactName { get;set; }
    }


       //Customers xxml file
       <?xml version="1.0" encoding="utf-8" ?>
       <Database Name="NORTHWND" xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007">
           <Table Name="dbo.Customers" Member="Customers">
              <Type Name="Customers">
                 <Column Name="CustomerID" Member="ID"/>
                 <Column Name="CompanyName" Member="CompanyName"/>
                 <Column Name="ContactName" Member="ContactName"/>
              </Type>
          </Table>
      </Database>

   //And this is the code I use to linq the data:
   if(!IsPostBack)
   {
        DataContext ctx = new DataContext(ConfigurationManager.ConnectionStrings["customers"].ConnectionString , 
                                                  XmlMappingSource.FromUrl(Server.MapPath("~/Customers.xml")));

        var customers = from c in ctx.GetTable<Customers>()
                                select c;

        GridView1.DataSource = customers;
        GridView1.DataBind();

    }

当我运行代码时,我在 GridView.DataBind() 处收到此错误:

   Specified cast is not valid.
   Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
   Exception Details: System.InvalidCastException: Specified cast is not valid.

我在这里做错了什么?

4

1 回答 1

1

如果我没记错的话,Northwind 中的 CustomerID 列是一个 NVARCHAR ......
所以将您的 Customer 类更改为:

public string ID { get;set; }
于 2012-12-15T14:42:13.227 回答