如何使用URL查询处理WCF-OData中的延续?

时间:2011-04-01 15:56:09

标签: .net wcf odata

我正在使用指向OData端点的WCF数据服务。如果我使用DataServiceQuery,我可以毫无困难地管理延续。

var collection = new DataServiceCollection<T>();
collection.LoadCompleted += (sender, e) =>
    {
        if (e.Error != null)
        {
            callback(null, e.Error);
            return;
        }

        var thisCollection = (DataServiceCollection<T>) sender;
        if (thisCollection.Continuation != null)
        {
            thisCollection.LoadNextPartialSetAsync();
        }
        else
        {
            var items = thisCollection.ToList();
            callback(items, e.Error);
        }
    };
collection.LoadAsync(query);

但是,我不知道如何为DataServiceContext.BeginExecute(string url,...)方法做同样的事情。

_odataContext.BeginExecute<T>(new Uri(requestUrl), x =>
{
    var items = _odataContext.EndExecute<T>(x);

    //not sure how to get the rest of the items with this method
});

如何使用基于网址的查询方法,但仍然可以获得持续支持?

3 个答案:

答案 0 :(得分:3)

同步样本(使其更简单):

var r = ctx.Execute<Product>(new Uri("http://services.odata.org/Northwind/Northwind.svc/Products"));
QueryOperationResponse<Product> response = (QueryOperationResponse<Product>)r;
response.Count();
Console.WriteLine(response.GetContinuation());

简而言之,Execute方法返回QueryOperationResponse的实例,它实现了IEnumerable,但也暴露了延续。

答案 1 :(得分:2)

为了完整性,这是URL查询的延续之后的完整功能。

public void ExecuteFullQuery<T>(Uri requestUrl, Action<IEnumerable<T>> callback)
{
    var list = new List<T>();
    ExecuteFullQueryImpl(requestUrl, list, callback);
}

private void ExecuteFullQueryImpl<T>(Uri requestUrl, List<T> items, Action<IEnumerable<T>> callback)
{
    _odataContext.BeginExecute<T>(requestUrl, x =>
    {
        var results = _odataContext.EndExecute<T>(x);
        if (results != null)
            items.AddRange(results.ToList());

        var response = (QueryOperationResponse<T>)results;
        var continuation = response.GetContinuation();
        if (continuation != null)
        {
            ExecuteFullQueryImpl(continuation.NextLinkUri, items, callback);
        }
        else
        {
            callback(items);
        }
    },
    null);
}

答案 2 :(得分:2)

使用惰性枚举器

public IEnumerable<Product> GetProducts()
{
    Uri request = new Uri("http://services.odata.org/Northwind/Northwind.svc/Products");

    var response = (QueryOperationResponse<Product>)ctx.Execute<Product>(request);

    while (true)
    {
        foreach (Product p in response)
        {
            yield return p;
        }

        var continuation = response.GetContinuation();
        if (continuation == null)
        {
            yield break;
        }

        response = ctx.Execute(continuation);
    }
}