LINQ to SQL出错:指定的强制转换无效

Mah*_*aha 5 sql linq

您好我正在尝试学习LINQ,在LINQ to SQL中我有以下异常:这是Manning出版物Linq In Action的示例代码.怎么了?

        DataContext db = new DataContext("E:\\Mahesh\\TempFolder\\DB\\NORTHWND.MDF");

        var contacts =
            from contact in db.GetTable<Contact>()
            where contact.City == "Paris"
            select contact;

        foreach (Contact aContact in contacts)
            Console.WriteLine("Bonjour " + aContact.Name);
        Console.Read();
    }
}

[Table(Name = "Customers")]
class Contact
{
    [Column(IsPrimaryKey = true)]
    public int CustomerID { get; set; }
    [Column(Name = "ContactName")]
    public string Name { get; set; }
    [Column]
    public string City { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

错误

例外细节:

System.InvalidCastException was unhandled
HResult=-2147467262
Message=Specified cast is not valid.
Source=System.Data
StackTrace:
   at System.Data.SqlClient.SqlBuffer.get_Int32()
   at Read_Contact(ObjectMaterializer`1 )
   at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
   at LinqDemo.Program.Main(String[] args) in c:\Users\MAHESH\Desktop\TechNode\C#\MyTechDos\LinqDemo\LinqDemo\Program.cs:line 51
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
InnerException: 
Run Code Online (Sandbox Code Playgroud)

Joh*_*ogo 5

如果我的内存服务,Northwind中的Customers表没有CustomerID作为int(我认为它的NVARCHAR).如果手动编写Contact类,而不是让LINQ to SQL生成它,请确保类上的类型与数据库表中的类型匹配

编辑:从这个链接http://msdn.microsoft.com/en-us/library/bb399575(v=vs.90).aspx倾向于认为CustomerID字段不是INT而是NVARCHAR(或NCHAR) )