Created
December 3, 2019 19:08
-
-
Save vendettamit/6c132a887a8cb3e3825b59b05e1d563d to your computer and use it in GitHub Desktop.
Utility method to detect long string and targeted column that's causing exception "String or binary data would be truncated"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void FindLongStrings(object testObject) | |
{ | |
foreach (FieldInfo propInfo in testObject.GetType().GetFields()) | |
{ | |
foreach (ColumnAttribute attribute in propInfo.GetCustomAttributes(typeof(ColumnAttribute), true)) | |
{ | |
if (attribute.DbType.ToLower().Contains("varchar")) | |
{ | |
string dbType = attribute.DbType.ToLower(); | |
int numberStartIndex = dbType.IndexOf("varchar(") + 8; | |
int numberEndIndex = dbType.IndexOf(")", numberStartIndex); | |
string lengthString = dbType.Substring(numberStartIndex, (numberEndIndex - numberStartIndex)); | |
int maxLength = 0; | |
int.TryParse(lengthString, out maxLength); | |
string currentValue = (string)propInfo.GetValue(testObject); | |
if (!string.IsNullOrEmpty(currentValue) && maxLength != 0 && currentValue.Length > maxLength) | |
Console.WriteLine(testObject.GetType().Name + "." + propInfo.Name + " " + currentValue + " Max: " + maxLength); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment