5

I'm using entity framework in an asp.net mvc 3.0 application. I'm using a table-valued function to do a full text search on one of my database tables. I have set the return type to an object of type Request. Then I feed the results into an expression builder that does a contains operation on the Requests from a list of entities that the user has access to. This is the code.

List<int> UserEntities = db.UserEntities
                              .Where(x => x.UserID.Equals(usr.ID))
                              .Select(x => x.EntityID).ToList();

var requests = db.SearchRequest(keyword)
    .Where(BuildContainsExpression<Request, int>(x => x.EntityID, UserEntities));

//Expression Builder for Contains SQL functionality
static Expression<Func<TElement, bool>> BuildContainsExpression<TElement, TValue>(
     Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values)
{
    if (null == valueSelector) { throw new ArgumentNullException("valueSelector"); }
    if (null == values) { throw new ArgumentNullException("values"); }
    ParameterExpression p = valueSelector.Parameters.Single();
    // p => valueSelector(p) == values[0] || valueSelector(p) == ...
    if (!values.Any())
    {
        return e => false;
    }
    var equals = values.Select(
            value => (Expression)Expression.Equal(
                                      valueSelector.Body, 
                                      Expression.Constant(value, typeof(TValue))));
    var body = equals.Aggregate<Expression>(
                   (accumulate, equal) => Expression.Or(accumulate, equal));
    return Expression.Lambda<Func<TElement, bool>>(body, p);
}

The second line will not build. The compiler is telling me that the SearchRequest procedure is returning ObjectResult but needs IQueryable. How to I convert the ObjectResult to IQueryable?

Jan
  • 15,802
  • 5
  • 35
  • 59
Dale Marshall
  • 1,137
  • 7
  • 20
  • 42
  • Can't you just call `AsIQueryable()` ? – Jan Nov 26 '12 at 15:44
  • 1
    That was exactly what I was looking for. I was confused because I was looking for a .ToQueryable. I didn't even think of AsQueryable. If you write it as an answer I will accept it. – Dale Marshall Nov 26 '12 at 15:51

2 Answers2

7

Just use the extension method Queryable.AsQueryable<T>().

Jan
  • 15,802
  • 5
  • 35
  • 59
1

Add the line

using System.Linq

and the extension methods will be available.

Nam Le
  • 1,126
  • 7
  • 7