2015-04-23 7 views
5

Po zaktualizowaniu sugestię nadal jestem uzyskiwanie błądJak uzyskać StringLength z DataAnnotations

Próbowałem zarówno z .SingleOrDefault() lub FirstOrDefault()

enter image description here

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; } 
} 

Odpowiedz

4

I stanie zorientowali się, przetestowane i jego pracy super, w przypadku, gdy ktoś inny szuka!

StringLengthAttribute strLenAttr = typeof(EmployeeViewModel).GetProperty(name).GetCustomAttributes(typeof(StringLengthAttribute), false).Cast<StringLengthAttribute>().SingleOrDefault(); 
    if (strLenAttr != null) 
    { 
    int maxLen = strLenAttr.MaximumLength; 
    } 
1

można uzyskać odpowiedź od When you get theLINQ Error “Sequence contains no elements”, this is usually because you are using the First() or Single() command rather than FirstOrDefault() and SingleOrDefault().

Więc trzeba spróbować użyć SingleOrDefault() zamiast Single() jak

var attribute = modelClass.GetProperties() 
          .Where(p => p.Name == propertyName) 
          .SingleOrDefault() 
          .GetCustomAttributes(typeof(StringLengthAttribute), true) 
          .SingleOrDefault() as StringLengthAttribute; 
+0

jeśli masz "Minimalna długość = 1", to wymuszasz, aby mieć minimalną długość? mimo że te pola są opcjonalne? –

+0

@AbuHamzah: - Zaktualizowano moją odpowiedź. Proszę sprawdzić! –

+0

Zaktualizowałem moje pytanie, wciąż otrzymuję ten sam błąd –

0

Czy próbujesz pokazać długość jako część komunikatu o błędzie? Jeśli tak, uważam, że można po prostu umieścić ...

public class EmployeeViewModel 
{   
    [StringLength(20, ErrorMessage = "{0} cannot be longer than {1} characters.")] 
    public string Name{ get; set; } 
} 
+0

nie, używam długość dla innych celów sprawdzania poprawności, ale nie dla komunikatu o długości show show –

0
var maxLength = typeof(EmployeeViewModel) 
        .GetProperty("Name") 
        .GetCustomAttributes<StringLengthAttribute>() 
        .FirstOrDefault() 
        .MaximumLength; 
0

Jak właśnie zwalczanie tego, pomyślałem, że podać kod LINQPad gram około z. Jest wystarczająco kompletny, aby działać w Linqpad, wystarczy dodać import, jeśli chcesz poznać.

Uwaga, gdzie komentuję bit, którego faktycznie potrzebujesz. Czasami trudno było zaadaptować kod bez kontekstu.

///The rest of the code given as context as I'm working on a T4 template to create Model classes from Datalayer classes, so the iteration is required in my case 
void Main() 
{ 
    CVH p = new CVH(); 
    Type t = p.GetType(); 

    foreach (PropertyInfo prop in t.GetProperties()) //Iterating through properties 
    { 
     foreach (var facet in prop.GetCustomAttributes()) //Yank out attributes 
     { 
     //The bit you need 
      if ((Type)facet.TypeId == typeof(StringLengthAttribute)) //What type of attribute is this? 
      { 
       StringLengthAttribute _len = (StringLengthAttribute)facet; //Cast it to grab Maximum/MinimumLengths etc. 
       Console.WriteLine($"My maximum field length is { _len.MaximumLength}"); 
       //End of the bit you need 
       Console.WriteLine(_len.MinimumLength);    
      } 
     } 
    } 
} 
///Test class with some attributes 
public class CVH 
{ 
    [StringLength(50)] 
    [DataType(DataType.PhoneNumber)] 
    public string phone_1 { get; set; } 
    [Required(ErrorMessage = "id is required")] 
    public int id { get; set; } 
    [Required(ErrorMessage = "id is required")] 
    public int contact_id { get; set; } 
} 
Powiązane problemy