我有一个模型类,它有一个描述属性,其数据注释属性为 StringLength,长度设置为 100 个字符。当此属性超过 100 个字符并且实体框架尝试保存此属性时,我收到以下错误。
[StringLength(100, ErrorMessage = "Description Max Length is 100")]
public string Description { get; set; }
Error:
“一个或多个实体的验证失败。有关更多详细信息,请参阅“EntityValidationErrors”属性”
我不确定这是否有助于形成解决方案,但我正在使用实体框架 CTP5 和代码优先。
我想要做的是,如果描述超过 100 个字符,则删除超过 100 个字符的字符,以便可以存储描述并且不会引发错误。
我相信我应该能够手动使用 DataAnnotation 属性 StringLength 来帮助我识别描述的有效长度,然后使用 SubString 删除超过有效数量的任何字符。
有谁知道在这种情况下如何使用 DataAnnotation?或者还有其他可用的选择吗?
Update我按照 BrokenGlass 的建议进行了操作,这里是我的实现,如果:
public static class DataAnnotation
{
public static int? GetMaxLengthFromStringLengthAttribute(Type modelClass, string propertyName)
{
int? maxLength = null;
var attribute = modelClass.GetProperties()
.Where(p => p.Name == propertyName)
.Single()
.GetCustomAttributes(typeof(StringLengthAttribute), true)
.Single() as StringLengthAttribute;
if (attribute != null)
maxLength = attribute.MaximumLength;
return maxLength;
}
}
int? maxLength = DataAnnotation.GetMaxLengthFromStringLengthAttribute(typeof(Car), "Description");
if(maxLength != null && car.Description.Length > maxLength)
car.Description = car.Description.Substring(0, maxLength.Value);
BarDev