6
I have a class to search for DisplayName
of my entities, where I pass the entity and class returns a list with the real values and name of each attribute of the entity.
My problem itself is when I do the search and some attribute in the entity does not have the annotation DisplayName
. I get the error of 'System.NullReferenceException'
.
I tried to put where
for when you find some value null
not list, but my mistake occurs when 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 don’t want them to be selected.
Follows the codes:
Advanced research
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();
}
}
Entidade Cliente
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 a better understanding:
The downvoter can you tell me what’s wrong with the answer so I can fix it?
– Jéf Bueno
Funny these downvoter without justification, could have a way to avoid this; Downvoter only be valid with a comment justifying and etc...
– Harlan Gomes Nascimento
It is, but it’s complicated. This has already been quite discussed here on the site, but it really is a very delicate situation. Anyway, I wait feedback so I can fix the answer.
– Jéf Bueno
@jbueno understood its placement, when I put the operated
?
I can’t find the available attribute anymoreDisplayName
using the Ctrl-Space command..Where(p => p.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName != null)
OBS: it wasn’t me who denied your answer. I appreciate the help– Aprendiz
@Learner What language version are you using?
– Jéf Bueno