String or binary data would be truncated. linq exception, cant find which field has exceeded max length.
i have around 350 fields. i checked each and every textbox maxlength with database field maxlength, everything seems to be correct, but i still get the exception.
please help
Best Answer
Troubleshooting this error with 350 fields can be extremely difficult, and SQL Server Profiler isn't much help in this case (finding the long string in the generated SQL is like finding a needle in a haystack).
So, here is an automated way to find the actual strings that are exceeding the database size limit. This is a solution that's out there on the internet, in various forms. You probably don't want to leave it in your production code, since the attribute/property searching is pretty inefficient, and it'll add extra overhead on every save. I'd just throw it in your code when you encounter this problem, and remove it when you're done.
How it works: it iterates over all properties on an object you're about to save, finding the properties with a LINQ to SQL
ColumnAttribute
. Then, if theColumnAttribute.DbType
contains "varchar", you know it's a string and you can parse that part of the attribute to find the maximum length.Here's how to use it:
And here's the method:
Update 12/03/2019 - This answer is referenced on Linqpad.net website for the same error. In Linqpad (version 5) (that uses LinqToSql) the columns are no longer listed as properties instead they are fields . Use the following to iterate through fields: