Search code examples
c#entity-frameworklinq

Get property from object and check if it contains value


I am trying to use get property from object and check if that property contains certain value:

Method to get property looks like:

public static object GetProp(object obj, string propName, value)
{
    return obj.GetType().GetProperty(propName).GetValue(obj).Contains(value);
}

This will get me object value.

And usage is (or actually what I am trying to achieve is):

string value = this._predicateFilter.GetValueOrDefault(refName, string.Empty);

if (!string.IsNullOrEmpty(value))
{
    predicate.And(c => Assets.Extensions.GetProp(c, "name", "value to compare"));
} 

I am getting an exception:

'object' does not contain a definition for 'Contains' and the best extension method overload 'Queryable.Contains (IQueryable, string)' requires a receiver of type 'IQueryable'

And I think problem is something with linq and Entity Framework can't execute that method inside its body.

I could use nasty solution like:

string firstname = this._predicateFilter.GetValueOrDefault("Firstname", string.Empty);

if (!string.IsNullOrEmpty(firstname))
{
    predicate.And(c => c.Firstname.Contains(firstname));
}

string lastname = this._predicateFilter.GetValueOrDefault("Lastname", string.Empty);

if (!string.IsNullOrEmpty(lastname))
{
    predicate.And(c => c.Lastname.Contains(lastname));
}

Which works fine, but I wold prefer less code - what am I missing?

Oh and I'm using

var predicate = PredicateBuilder.New<Candidate>();

from linqKit


Solution

  • PropertyInfo.GetValue returns an object which you are trying to use as an IQueryable<T>.

    The code is telling you exactly what the error is object does not contain a (extension)method for Contains. Also in the updated code you missed the identifier off of value in the method signature and have the return type as object when you will always be returning a bool.

    So fix those errors and before calling Contains cast it to an IQueryable<T>:

    public static bool GetProp(object obj, string propName, string value)
    {
        object o = obj.GetType().GetProperty(propName).GetValue(obj);
    
        IQueryable<object> queryable = o as IQueryable<object>;
        if (queryable != null)
        {
            return queryable.Contains(value);
        }
    
        return false; //Some other default
    }