我有一个模型类,它有一个描述属性,其数据注释属性为 StringLength,长度设置为 100 个字符。当此属性超过 100 个字符并且 Entity Framework 尝试保存此属性时,我收到以下错误。
[StringLength(100, ErrorMessage = "Description Max Length is 100")]
public string Description { get; set; }
错误:
“一个或多个实体的验证失败。有关详细信息,请参阅‘EntityValidationErrors’属性”
我不确定这是否有助于形成解决方案,但我使用的是 Entity Framework CTP5 和 Code First。
我想做的是,如果描述超过 100 个字符,则删除超过 100 个字符的字符,以便可以存储描述并且不会引发错误。
我相信我应该能够手动使用 DataAnnotation 属性 StringLength 来帮助我确定描述的有效长度,然后使用 SubString 删除超过有效长度的任何字符。
有人知道在这种情况下如何使用 DataAnnotation 吗?或者还有其他可用的选项吗?
更新 我按照 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);
酒吧开发
最佳答案
你总是可以使用反射来检查属性值,尽管如果你能绕过它,这种方法并不是最好的——它并不漂亮:
var attribute = typeof(ModelClass).GetProperties()
.Where(p => p.Name == "Description")
.Single()
.GetCustomAttributes(typeof(StringLengthAttribute), true)
.Single() as StringLengthAttribute;
Console.WriteLine("Maximum Length: {0}", attribute.MaximumLength);
关于C# 如何使用 DataAnnotations StringLength 和 SubString 删除文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5287752/