简体   繁体   中英

Error in C# using LINQ to SQL and sqlmetal System.InvalidCastException: Specified cast is not valid

When running some code I've written on our production server or another developers machine it crashes on this line.

Ac_CalcDetail xy = db.Ac_CalcDetails.Where(chld => chld.CalcIdent.Equals(CalcIdent)).First();

CalcIdent is just a guid as a string.

I've ran sqlmetal on my local database where Ac_CalcDetail is our main table to create this strongly typed code and the class Ac_CalcDetail. The problem is when i run the code here on the production server or on one of the other developer's machines. We've been using LINQ for well over a year now and never had any problems so really confused about this. Previously the exceptions I've been getting have been very specific saying which field is missing which is brilliant, but from my research apparently this error could be a certain field having the wrong datatype. nightmare and completelely impossible to debug through just this error.

I think the only solution at present is to just back my database up in SQL Server Management Studio and then get everyone else to use this. As we're a small company we tend to just do whatever we want to our own databases, then create various SQL scripts to put on a dropbox folder to get our databases in sync (or at least what we thought was in sync). Not sure if this implies that we'll either have to stop using LINQ or start using some more advanced SQL stuff (SQL repositories or SQL database compare tools or etc).

It's very odd though as I know our databases haven't been completely the same for ages (if ever) so not sure why this error is happening now and why the error message doesn't say anything!

Change

Ac_CalcDetail xy

to

var xy

than try debugging it. But clearly looks like you got some Types wrong.

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