Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<object>.Contains Expression Tree

Tags:

c#

lambda

linq

I would like to build an Expression that would equate to expected...

Expression<Func<ReferencedEntity, bool>> expected = (ReferencedEntity referencedEntity) => foreignKeys.Contains(referencedEntity.Id);
Expression<Func<ReferencedEntity, bool>> actual;

foreignKeys type is a List<object>

Here is what I have so far and I think it would use Expression.Call() method but not sure exactly how to go about it.

ParameterExpression entityParameter = Expression.Parameter(typeof(TReferencedEntity), "referencedEntity");
MemberExpression memberExpression = Expression.Property(entityParameter, "Id");
Expression convertExpression = Expression.Convert(memberExpression, typeof(object)); //This is becuase the memberExpression for Id returns a int.

//Expression containsExpression = Expression.Call(????

//actual = Expression.Lambda<Func<TReferencedEntity, bool>>(????, entityParameter);

Thanks for you help.

like image 940
bytebender Avatar asked Nov 30 '22 12:11

bytebender


1 Answers

Here is the solution I couldn't have done it without Samuel's suggestion though...

    /// <summary>
    /// 
    /// </summary>
    /// <param name="foreignKeys"></param>
    /// <returns></returns>
    private Expression<Func<TReferencedEntity, bool>> BuildForeignKeysContainsPredicate(List<object> foreignKeys, string primaryKey)
    {
        Expression<Func<TReferencedEntity, bool>> result = default(Expression<Func<TReferencedEntity, bool>>);

        try
        {
            ParameterExpression entityParameter = Expression.Parameter(typeof(TReferencedEntity), "referencedEntity");
            ConstantExpression foreignKeysParameter = Expression.Constant(foreignKeys, typeof(List<object>));
            MemberExpression memberExpression = Expression.Property(entityParameter, primaryKey);
            Expression convertExpression = Expression.Convert(memberExpression, typeof(object));
            MethodCallExpression containsExpression = Expression.Call(foreignKeysParameter
                , "Contains", new Type[] { }, convertExpression);

            result = Expression.Lambda<Func<TReferencedEntity, bool>>(containsExpression, entityParameter);

        }
        catch (Exception ex)
        {
            throw ex;
        }

        return result;
    }
like image 162
bytebender Avatar answered Feb 16 '23 15:02

bytebender