Home > Blockchain >  Custom Linq method could not be translated
Custom Linq method could not be translated

Time:12-24

I created one custom extension method to represent SQL 'IN' operation where I just wanted to make it reusable and more straight-forward.

 public static bool In<T>(this T source, params T[] list)
        {
            return list.Contains(source);
        }

Problem is that I just can't make it work, this is how I call it:

dataSource.Where(s => s.Id.In(6, 8)).Select(...);

This approach works though:

dataSource.Where(d => new int[] { 6, 8 }.Contains(d.Id)).Select(...)

I keep receiveing that "The LINQ .Where(b => b.Id\r\n .In(__n_0))' expression could not be translated..."

CodePudding user response:

I once wrote this method, utilizing expression trees, basically, you would do this:

dataSource.In(s => s.Id, 6, 8).Select(...);

Code:

    public static IQueryable<TSource> In<TSource, TMember>(this IQueryable<TSource> source,
 Expression<Func<TSource, TMember>> identifier, params TMember[] values)
      {
          var parameter = Expression.Parameter(typeof(TSource), "m");
          var inExpression = GetExpression(parameter, identifier, values);
          var theExpression = Expression.Lambda<Func<TSource, bool>>(inExpression, parameter);
          return source.Where(theExpression);
      }

internal static Expression GetExpression<TSource, TMember>(ParameterExpression parameter, Expression<Func<TSource, TMember>> identifier, IEnumerable<TMember> values)
{
    var memberName = (identifier.Body as MemberExpression).Member.Name;
    var member = Expression.Property(parameter, memberName);
    var valuesConstant = Expression.Constant(values.ToList());
    MethodInfo method = typeof(List<TMember>).GetMethod("Contains");
    Expression call = Expression.Call(valuesConstant, method, member);
    return call;
}

available on GitHub and NuGet with other LINQ extensions:

  • Related