捕获并解决实体验证错误



我使用代码优先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; }

从我所读到的一切,这是不可能在ValidationAttributeIsValid()调用期间改变属性的值。我找不到任何具体说明这是不可能的,但所有迹象都表明不可能。

最新更新