LINQ select from SQL Server CE: Specified Cast is

2019-08-12 04:47发布

问题:

Ok first off, Hi every one this is my first post.

Right now to business, I have created an SQLCE database, created the data context and all the mappings and have successfully filled the database with a load of data. So far so good, now if I want to retrieve the data I get a problem.

Code for getting data

var codes = (from c in App.BonusDatabase.tbRawData
             select c).ToList();

Running that I get Specified cast is not valid. I'm guessing there is a value somewhere it doesn't like, how can I find what the value is?

at System.Data.SqlServerCe.SqlCeDataReader.GetFloat(Int32 ordinal)
at Read_RAW(ObjectMaterializer`1 )
at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at BAT.Bonus.BonusRun(Int32 Week) in Bonus.cs:line 36
at BAT.Bonus.BonusRun() in Bonus.cs:line 25
at BAT.winMain.worker_DoWork(Object sender, DoWorkEventArgs e) in winMain.xaml.cs:line 91
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)

Edit: Ok as a cheat I copied the SQL create table query into a another program and got it to count how many times I had int, float, etc. The count is as expected. I then repeated this with the LINQ mapping and it has a matching count, so I don't think the mapping is wrong.

Edit 2: I just modified the above code to just select 1 field rather than everything like so

var codes = (from c in App.BonusDatabase.tbRawData
        select c.CODE).ToList();

This works fine but if I then change to another field

var codes = (from c in App.BonusDatabase.tbRawData
        select c.PPH).ToList();

I get the error. So is this the one thats playing up? If so what could be the problem as its declared as float in both SQL database and my mappings

回答1:

It looks like the mapping between your class and the table has a property mapped to a database field with an incompatible type, e.g. you have an int property mapped to an nvarchar db field.



回答2:

How is tbRawData declared? Maybe one of the field definitions doesn't match the field in the database.