简体   繁体   中英

Linq to sql poco approach specified cast is not valid

Hi I am trying to learn LINQ TO SQL and am trying to map the data using the POCO approach but I seem to be getting an error.Here is my code I am using the NORTHWIND database Customers table:

   //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();

    }

When I run the code I get this error at 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.

What am I doing wrong here?

The CustomerID column in Northwind is an NVARCHAR if I remember correctly...
So change your Customer class to:

public string ID { get;set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM