Skip to content

Instantly share code, notes, and snippets.

@vendettamit
Created December 3, 2019 19:08
Show Gist options
  • Save vendettamit/6c132a887a8cb3e3825b59b05e1d563d to your computer and use it in GitHub Desktop.
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"
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