sql - LINQ to SQL 错误 : specified cast is not valid

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

Error

异常详细信息:

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: 

最佳答案

如果我没记错的话,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)

关于sql - LINQ to SQL 错误 : specified cast is not valid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11050614/

相关文章:

sql - Spark SQL : NULL handling in IF

MySQL 将值复制到另一个表

sql - 使用 Access SQL 进行分组排名

sql - REST Api 中的原始 SQL 查询

c# - .ForEach() 是 C# 语言的哪一部分?

c# - 如何将表达式 x=>!x 重写为 x=>x!=true 并将 x=>x 重写为 x=>x==true

c# - 在 linq 中返回选择查询的最佳实践

SQL 查询 - 从特定行过滤值到结果

c# - 使用 linq 将逗号分隔的字符串转换为列表

.net - 在公共(public) .net 应用程序中使用执行 SQL 函数是否安全?