Skip to content
Advertisement

Error in LINQ to SQL: specified cast is not valid

Hi I am trying to learn LINQ, and in LINQ to SQL I have got following exception: This is a sample code from Linq In Action by Manning publications. Whats wrong?

        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

Exception details:

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:UsersMAHESHDesktopTechNodeC#MyTechDosLinqDemoLinqDemoProgram.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: 

Advertisement

Answer

If my memory serves, the Customers table in Northwind does not have CustomerID as int (I think its NVARCHAR). If you wrote the Contact class manually, instead of have LINQ to SQL generate it, make sure that the types on your class match the types in the database table

EDIT: From this link http://msdn.microsoft.com/en-us/library/bb399575(v=vs.90).aspx am inclined to think that the CustomerID field is not INT but NVARCHAR (or NCHAR for that matter)

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement