的StringLength更新建议后,我仍然得到错误如何从DataAnnotations
都尝试用.SingleOrDefault()
或FirstOrDefault()
我需要检索StringLength
标注值,在这里是我的代码,但我发现了以下错误。
我试图实现几乎从here相同的代码,但得到的错误:
Sequence contains no elements
public static class DataAnnotation
{
public static int GetMaxLengthFromStringLengthAttribute(Type modelClass, string propertyName)
{
int maxLength = 0;
var attribute = modelClass.GetProperties()
.Where(p => p.Name == propertyName)
.Single()
.GetCustomAttributes(typeof(StringLengthAttribute), true)
.Single() as StringLengthAttribute;
if (attribute != null)
maxLength = attribute.MaximumLength;
return 0;
}
}
//电话:
int length = DataAnnotation.GetMaxLengthFromStringLengthAttribute(typeof(EmployeeViewModel), "Name");
public class EmployeeViewModel
{
[StringLength(20, ErrorMessage = "Name cannot be longer than 20 characters.")]
public string Name{ get; set; }
}
如果你有'MinimumLength = 1',那么你正在执行有最小长度?即使这些字段是可选的? –
@AbuHamzah: - 更新我的答案。请检查! –
我更新了我的问题,仍然得到同样的错误 –