我使用代码优先EF 4.1插入数据到SQL Server数据库。当字符串属性的值大于映射中的最大值时,EF抛出一个DbEntityValidationException
,其EntityValidationsErrors
包含该问题的详细信息。
是否有任何方法以编程方式解决错误?
我特别想截断有问题的属性,记录一个"属性X截断"通知供以后使用,并重新尝试SaveChanges()
。
我已经创建了一个自定义的ValidationAttribute
,检查带注释的属性的长度,但不能弄清楚我是否可以同时改变属性的长度。
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;
}
}
}
我会在属性上添加一个StringLength
属性。
这篇文章不错http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx
[StringLength(64, "this needs to be less than 64")]
public string MyStringProperty { get; set; }
从我所读到的一切,这是不可能在ValidationAttribute
的IsValid()
调用期间改变属性的值。我找不到任何具体说明这是不可能的,但所有迹象都表明不可能。