Check that all fields of an entity is null

Asked

Viewed 1,590 times

5

I’m doing a verification of an entity view model in the C# and I have to validate if all fields are null, because I have to require at least 1 filter to continue the routine.

Doubt: What better simple and correct way to do this?

Obs: All fields are nullables.

if (!string.IsNullOrEmpty(filtroOrd.Aprovada) 
|| !string.IsNullOrEmpty(filtroOrd.Bloqueada) 
|| ...)

inserir a descrição da imagem aqui

3 answers

7


The answers already solve your problem and are very good. But I would like to contribute one more way to do also using reflection. The solution is the same after all, but I think it’s simpler and more readable.

The method below checks all properties of any object and returns true only if all property are nonzero.

public static bool VerificarPropriedadesNaoNulas<T>(this T obj)
{
    return typeof(T).GetProperties().All(a => a.GetValue(obj) != null);    
}

Method call:

var filtroOrd = new Filtro();
bool propriedadeNaoNulas = filtroOrd.VerificarPropriedadesNaoNulas();

An important point to emphasize that there are no other answers:

Reflection can be quite slow and should be used carefully. For this particular case I see no problem and I do not think you will notice considerable difference. However, your approach to the question by checking item by item in the if would undoubtedly be faster.

On the other hand, a great advantage in this approach using the Reflection is that even if you add new properties to your class, there will be no maintenance required in the method and you will avoid error in the application if your class is changed.

6

Well, I’d like to start by saying I don’t know if that’s the best way to do it, but you can use it Reflection, goes below:

bool TemAlgumaPropriedadeComValor(object myObject)
{
    foreach (PropertyInfo pi in myObject.GetType().GetProperties())
    {
        if (pi.PropertyType == typeof(string))
        {
            string value = (string)pi.GetValue(myObject);
            if (!string.IsNullOrEmpty(value))
                return true;
        }
    }
    return false;
}

I added in the .Net Fiddle for reference

6

Let’s create an extension method to validate if our Viewmodel has any null property.

To start we will create a base class so that all our Viewmodels inherit from it, so we can distinguish our Viewmodels from other classes in the project:

public abstract class ViewModelBase
{
    // Adicione propriedades que sejam comuns para todas suas ViewModels, aqui é apenas um exemplo.
    public int Identificador { get; set; }
}

Next we will make our specific Viewmodels inherit from our abstract class ViewModelBase, below an example:

public class PessoaViewModel : ViewModelBase
{
    public string Nome { get; set; }
    public string Sexo { get; set; }
    public DateTime? DataNascimento { get; set; }
    public int? QuantidadeFilhos { get; set; }
}

Next we will create a class that will contain only extension methods and in it we will have our method that will treat if our Viewmodel has some null field:

using System;
using System.Reflection;

namespace Projeto.Utilitario
{
    public static class Extensions
    {
        public static bool ViewModelPossuiAlgumaPropriedadeNulaOuVazia<T>(this T obj) where T : ViewModelBase
        {
            foreach (PropertyInfo propriedade in obj.GetType().GetProperties())
            {
                string value = Convert.ToString(propriedade.GetValue(obj));

                if (string.IsNullOrWhiteSpace(value))
                    return true;
            }

            return false;
        }
    }
}

To use our extension method just add the class namespace Extensions and call the method:

using Projeto.Utilitario;

static void Main(string[] args)
{
     PessoaViewModel pessoaViewModel = new PessoaViewModel
     {
         Nome = "Pedro",
         Sexo = "Masculino",
         DataNascimento = DateTime.Now
     };

    if (pessoaViewModel.ViewModelPossuiAlgumaPropriedadeNulaOuVazia())
    {
        // Implemente sua lógica caso possua algo vazio...
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.