2015-04-23 11 views
5

Dopo aver aggiornato il suggerimento sto ancora ottenere l'erroreCome ottenere lo StringLength da DataAnnotations

provato sia con .SingleOrDefault() o FirstOrDefault()

enter image description here

ho bisogno di recuperare il valore StringLength annotazione e qui è il mio codice ma sto ricevendo il seguente errore.

Ho cercato di attuare o meno lo stesso codice here ma ottenendo l'errore:

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

// chiamata:

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

risposta

4

ho potuto capito, testati e il suo grande lavoro, nel caso in cui se qualcun altro sta cercando!

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

È possibile ottenere la risposta da 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().

quindi è necessario provare a utilizzare SingleOrDefault() invece di Single() come

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

se si dispone di "MinimumLength = 1', quindi si impone di avere min-length? anche se i campi sono facoltativi? –

+0

@AbuHamzah: - Aggiornata la mia risposta. Si prega di controllare! –

+0

Ho aggiornato la mia domanda, ottenendo sempre lo stesso errore –

0

Stai cercando di mostrare la lunghezza come parte del messaggio di errore? Se è così credo che si può solo mettere ...

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

no, sto utilizzando la lunghezza per altri scopi di convalida ma non per il messaggio di errore della lunghezza di visualizzazione –

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

Mentre stavo solo affrontare questo, ho pensato di fornire il codice LINQPad Sto giocando intorno con. È abbastanza completo per essere eseguito in Linqpad, basta aggiungere le importazioni se si desidera esplorare.

Nota dove commento il bit di cui hai effettivamente bisogno. A volte ho trovato difficile adattare il codice senza alcun contesto.

///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; } 
} 
Problemi correlati