I have a class to search for DisplayName
of my entities, where I pass the entity and class returns a list with the actual values and name of each entity attribute.
My problem is when I search, and some attribute in the entity does not have the DisplayName
annotation. I get the error of 'System.NullReferenceException'
.
I tried to put where
to when I find some value null
does not list, but my error occurs when instantiating DisplayName
:
.Where(p => p.GetCustomAttribute<DisplayNameAttribute>().DisplayName != null)
How can I solve this problem? because I will have entities with some attributes without displayname
and I do not want them to be selected.
Follow the codes:
Advanced Search
public class PesquisaAvancada
{
public String Valor { get; set; }
public String Texto { get; set; }
public static List<PesquisaAvancada> camposPesquisa<T>()
{
return typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).Where(p => p.GetCustomAttribute<DisplayNameAttribute>().DisplayName != null).
Select(p => new PesquisaAvancada()
{
Valor = p.Name,
Texto = p.GetCustomAttribute<DisplayNameAttribute>().DisplayName
}).ToList();
}
}
Client Entity
public class Cliente
{
[Key]
[DisplayName("Identificador do Cliente")]
public Guid ClienteId { get; set; }
[Required]
// aqui removi o display name e acusa o erro
public String Nome { get; set; }
[Required]
[DisplayName("Nome Fantasia")]
public String Fantasia { get; set; }
}
Error:
An unhandled exception of type 'System.NullReferenceException' occurred in Model.dll
Image for better understanding: