0

I am trying to read up on this link:

https://stackoverflow.com/a/5971677

for defining custom functions in SSDL. However as it looks, the custom functions seem to be limited and can accept input parameters of primtive types. How can I pass IQueryable type as input parameters?

The above link shows simple custom function for Double.Parse. But I need more functionality than that.

Community
  • 1
  • 1
Jaggu
  • 6,298
  • 16
  • 58
  • 96
  • @moguzalp: Concern isn't writing helper class or architecting the solution. Concern is whether it is achievable or not! – Jaggu Mar 26 '12 at 09:54

1 Answers1

0

You can do it by linq expression tree and extension methods:

public static IQueryable<TSource> FilterConfirmable<TSource>(this IQueryable<TSource> source, ConfirmableFilter Confirmablefilter, [Optional, DefaultParameterValue("Confirmed")] string fieldName)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    if (Confirmablefilter == ConfirmableFilter.All)
    {
        return source;
    }
    Type sourceType = typeof(TSource);
    PropertyInfo confirmedProperty = sourceType.GetProperty(fieldName);
    if (confirmedProperty == null)
    {
        throw new InvalidOperationException(string.Format("Can not find a boolean column named \"{0}\", Consider to add a column named \"{0}\" in your linq select expression.", fieldName));
    }
    ParameterExpression o = Expression.Parameter(sourceType, "o");
    Expression equal = Expression.Equal(Expression.Property(o, confirmedProperty), Expression.Constant(Confirmablefilter == ConfirmableFilter.Confirmed));
    MethodCallExpression whereCallExpression = Expression.Call(typeof(Queryable), "Where", new Type[] { sourceType }, new Expression[] { source.Expression, Expression.Lambda<Func<TSource, bool>>(equal, new ParameterExpression[] { o }) });
    return source.Provider.CreateQuery<TSource>(whereCallExpression);
}

And use it like this:

q = from i in ctx.persons select i;
q = q.FilterConfirmable(...).where(...);
pylover
  • 7,670
  • 8
  • 51
  • 73
  • What is ConfirmableFilter? Is this your custom class? Also this won't work in subqueries. Will it? See my question: http://stackoverflow.com/questions/9869452/marc-gravells-dynamic-orderby-works-in-one-case-but-not-in-other – Jaggu Mar 26 '12 at 10:12