Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert an ObjectResult<T> to IQueryable<T>?

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?

like image 589
Dale Marshall Avatar asked Nov 26 '12 14:11

Dale Marshall


People also ask

What is IQueryable in C# with example?

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed. The definition of "executing an expression tree" is specific to a query provider.

What is difference between IEnumerable and IQueryable?

The major difference between IQueryable and IEnumerable is that IQueryable executes query with filters whereas IEnumerable executes the query first and then it filters the data based on conditions.


1 Answers

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

like image 188
Jan Avatar answered Oct 01 '22 18:10

Jan