I’m using code-first EF 4.1 to insert data into a SQL Server database. When a string property has a value longer than the maximum set in the mapping, EF throws a DbEntityValidationException whose EntityValidationsErrors contains the details of the issue.
Is there any way to resolve the errors programmatically?
Specifically I would like to truncate the property in question, record a “Property X Truncated” notification for later use and re-attempt the SaveChanges().
I’ve created a custom ValidationAttribute that checks the length of the annotated property but can’t figure out if I can change the property’s length at the same time.
public class TruncateAttribute : ValidationAttribute
{
public int TruncateLength { get; set; }
public TruncateAttribute(object truncateLength)
{
this.TruncateLength = (int) truncateLength;
}
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
var original = (string) value;
if (original.Length > this.TruncateLength)
{
value = original.Substring(0,
this.TruncateLength); // doesn't work
return new ValidationResult(
string.Format("{0} is longer than {1} characters",
validationContext.DisplayName, this.TruncateLength),
new[] {validationContext.MemberName});
}
else
{
return ValidationResult.Success;
}
}
}
From everything I’ve read, it is not possible to alter a property’s value during the
ValidationAttribute‘sIsValid()call. I can’t find anything that specifically says it isn’t possible but all signs point to no.