Verify that all fields in an entity are null

3

I'm doing a check of an entity view model in 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 is the simplest and best way to do this?

Obs : All fields are nullables .

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

    
asked by anonymous 27.12.2018 / 12:23

3 answers

4

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

Method that checks all properties of any object and returns true only if all properties are not null .

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();

I will only add a part that I think it is important to note that there are no other answers:

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

On the other hand, a major advantage of this approach is that even if you add new properties to your class, you will not need code maintenance and you will avoid application error if your class changes.

    
04.01.2019 / 12:21
5

Well, I'd like to start by saying that I do not know if this is the best way to do this, but you can use Reflection , 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 it on .Net Fiddle for reference

    
27.12.2018 / 12:42
5

Let's create an extension method to validate if our ViewModel has any null properties.

To begin with we will create a base class so that all of 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 only contain extension methods and we will have our method that will handle 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 simply add the namespace of class 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...
    }
}
    
27.12.2018 / 13:00