score:3

Accepted answer

Your best bet is to add a property or method on the type and use reflection to count the number of public properties that have a null value. Do not do it inside of the linq to sql call, it does not belong there.

public class Movie {
  // existing properties


  // this should not be mapped back to the EF store
  public int NumberOfNullPropValues => typeof(Movie).GetProperties().Count(x => x.GetValue(this, null) == null);
}

Note that this only works for reference types and Nullable<T>, it will not check for empty strings or for default values in the case the type is a struct (like 0 for int). Also if you want to check non public properties you need to pass binding flags to the GetProperties call

score:1

You can use Reflection

Like this (a method that returns how many null properties does an object have):

public int GetNullProperiesCount(object anyObject)
{
    var objType = anyObject.GetType();
    var nullCount = 0;

    foreach(var propInfo in objType.GetProperties())
    {
        if(propInfo.CanRead)
        {
           object val = propInfo.GetValue(anyValue, null);
           if(val == null) ++nullCount;
        }
    }
    return nullCount;
}

Then you can iterate through any collection and get how many null properties its items have.

score:0

Reflection may be expensive in terms of CPU cycles. I'd use a DataSet to read and examine the data. It's easy to do and does not impose the overhead of Linq


Related Articles