更新建议后,我仍然出现错误
尝试过.SingleOrDefault()
或FirstOrDefault()
我需要检索StringLength
批注值,这是我的代码,但是出现以下错误。
我尝试从here实现几乎相同的代码,但收到错误:
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; }
}
最佳答案
我能够弄清楚,进行测试并且可以很好地工作,以防万一其他人正在寻找!
StringLengthAttribute strLenAttr = typeof(EmployeeViewModel).GetProperty(name).GetCustomAttributes(typeof(StringLengthAttribute), false).Cast<StringLengthAttribute>().SingleOrDefault();
if (strLenAttr != null)
{
int maxLen = strLenAttr.MaximumLength;
}
关于c# - 如何从DataAnnotations获取StringLength,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29824779/