开发者

Implementing IQueryable.Count

开发者 https://www.devze.com 2023-01-27 03:16 出处:网络
I\'m working on an IQueryable provider. In my IQueryProvider I have the following code: public TResult Execute<TResult>(Expression expression)

I'm working on an IQueryable provider. In my IQueryProvider I have the following code:

public TResult Execute<TResult>(Expression expression)
{
    var query = GetQueryText(expression);

    // Call the Web service and get the results.
    var items = myWebService.Select<TResult>(query);

    IQueryable<TResult>开发者_运维百科; queryableItems = items.AsQueryable<TResult>();
    return (TResult)queryableItems;
}

GetQueryText does all the leg work and works out the query string for the expression tree. This is all working well, so Where, OrderBy and Take are sorted. The webservice supports a count query using the following:

int count = myWebService.Count(query);

But I can't get my head round where I put this in the IQueryable or IQueryProvider.

I've basically worked from reading tutorials and open source examples, but can't seem to find one that does Count.


The answer appears simpler than I first thought. This blog post helped:

The Execute method is the entry point into your provider for actually executing query expressions. Having an explicit execute instead of just relying on IEnumerable.GetEnumerator() is important because it allows execution of expressions that do not necessarily yield sequences. For example, the query “myquery.Count()” returns a single integer. The expression tree for this query is a method call to the Count method that returns the integer. The Queryable.Count method (as well as the other aggregates and the like) use this method to execute the query ‘right now’.

I did some debugging and for a query of myContext.Where(x => x.var1 > 5) Execute is called and TResult is an IEnumerable<MyClass>

For myContext.Where(x => x.var1 > 5).Count() Execute is called and TResult is an int

So my Execute method just needs to return appropriately.

0

精彩评论

暂无评论...
验证码 换一张
取 消