Po zaktualizowaniu sugestię nadal jestem uzyskiwanie błądJak uzyskać StringLength z DataAnnotations
Próbowałem zarówno z .SingleOrDefault()
lub FirstOrDefault()
muszę pobrać wartość StringLength
adnotacji i tutaj jest mój kod, ale otrzymuję następujący błąd.
starałem się wdrożyć prawie ten sam kod z here ale otrzymuję błąd:
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;
}
}
// wywołanie:
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; }
}
jeśli masz "Minimalna długość = 1", to wymuszasz, aby mieć minimalną długość? mimo że te pola są opcjonalne? –
@AbuHamzah: - Zaktualizowano moją odpowiedź. Proszę sprawdzić! –
Zaktualizowałem moje pytanie, wciąż otrzymuję ten sam błąd –