List <object> .Contains Expression Tree

I would like to build an expression that will fit the expected ...

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

Type foreignKeys is a List<object>

Here is what I have so far, and I think he will use the Expression.Call () method, but not sure how to do 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 the help.

+4
source share
2 answers

Here is a decision I could not have made 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; } 
+10
source

I do not know the solution, but I know how you could get it. Create a dummy function that takes Expression<Func<ReferencedEntity, bool>> and passes it your lambda. And using the debugger, you can check how the compiler created an expression for you.

+8
source

Source: https://habr.com/ru/post/954786/


All Articles