tags:

views:

289

answers:

2

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.

+5  A: 

I don't know the solution, but I know how you could get it. Create a dummy function that takes in an Expression<Func<ReferencedEntity, bool>> and pass it your lambda. And using a debugger you can examine how the compiler created the expression for you.

Samuel
Getting me a bit further... Thanks
J.13.L
Thanks for your help gave you an upvote...
J.13.L
+2  A: 

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;
 }
J.13.L