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?
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.
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.
Just use the extension method Queryable.AsQueryable<T>()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With