Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 捕获并解决实体验证错误_C#_.net_Entity Framework 4.1 - Fatal编程技术网

C# 捕获并解决实体验证错误

C# 捕获并解决实体验证错误,c#,.net,entity-framework-4.1,C#,.net,Entity Framework 4.1,我使用CodeFirstEF4.1将数据插入SQL Server数据库。当字符串属性的值长于映射中设置的最大值时,EF抛出一个DbEntityValidationException,其EntityValidationErrors包含问题的详细信息 有没有办法通过编程解决错误 具体来说,我想截断有问题的属性,记录一个“property X Truncated”通知供以后使用,然后重新尝试SaveChanges() 我创建了一个自定义的ValidationAttribute,它检查带注释属性的长度,

我使用CodeFirstEF4.1将数据插入SQL Server数据库。当字符串属性的值长于映射中设置的最大值时,EF抛出一个
DbEntityValidationException
,其
EntityValidationErrors
包含问题的详细信息

有没有办法通过编程解决错误

具体来说,我想截断有问题的属性,记录一个“property X Truncated”通知供以后使用,然后重新尝试
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
属性

这篇文章不错


从我读到的所有内容来看,在
ValidationAttribute
IsValid()
调用期间,不可能更改属性的值。我找不到任何明确说明这是不可能的,但所有迹象都表明不可能

[StringLength(64, "this needs to be less than 64")]
public string MyStringProperty { get; set; }