After updating the offer, I still get the error message
Tried both with .SingleOrDefault() and FirstOrDefault()

I need to get StringLength annotation StringLength , and here is my code, but I get the following error.
I tried to implement almost the same code from here , but getting an error:
The 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; } }
// call:
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; } }
source share