【问题标题】:Using where clause with continuation in oData client using C#在使用 C# 的 oData 客户端中使用带有延续的 where 子句
【发布时间】:2020-07-15 05:04:06
【问题描述】:

我正在使用 Microsoft oData 客户端从第三方 API 检索用户信息。我有以下代码。

var query = Context.Users.Where(x => x.username.EndsWith("10"));
var result = query.ToList().Select(x => x.username);

但是,这只会返回 100 条记录。我可以使用下面的代码来检索所有没有条件的记录;

 DataServiceCollection<User> users = new DataServiceCollection<User>(
                    Context.Users
                );

 while (users.Continuation != null)
 {
     //use the token to query for more users
     //and load the results back into the collection
     users.Load(
         Context.Execute<User>(users.Continuation)
     );
     //print the current count of users retrieved
     Console.WriteLine(users.Count);
  }

如何将两者结合起来?即检索条件为 (x.username.EndsWith("10")) 的所有记录。

【问题讨论】:

    标签: c# rest odata


    【解决方案1】:

    我会说一次只获取 100 行是一个好习惯。但是您可以使用 oDatas $top 来获取超过 100 行。 Microsoft oData 客户端为此使用 Take 函数:https://docs.microsoft.com/en-us/odata/client/query-options

    我应该能够简单地将两者结合起来:

    var result= Context.Users.Where(x => x.username.EndsWith("10")).Take(1000).Select(x => x.username);
    

    【讨论】:

    • 否,第二个选项不会同时检索记录。它只会确保获取所有记录。 “Take”将一次检索所有记录。
    【解决方案2】:

    我在 oData Client 版本 7.6.2 中使用这样的查询,但我认为它也可以在较新的版本中使用。

    var users = new List<User>();
    DataServiceQueryContinuation<User> nextLink = null;
    var query = Context.Users.Where(x => x.username.EndsWith("10")) as DataServiceQuery<User>;
    var response = await query.ExecuteAsync() as QueryOperationResponse<User>;
    do
    {
        if (nextLink != null)
        {
            response = await Context.ExecuteAsync<User>(nextLink) as QueryOperationResponse<User>;
        }
        users.AddRange(response);
    }
    while ((nextLink = response.GetContinuation()) != null);
    

    【讨论】:

    • 嗨,Mikael,我需要你的例子,但是如果你想在那里有 where 子句,那么第二次调用下一个链接怎么样?在:if (nextLink != null) { response = await Context.ExecuteAsync&lt;User&gt;(nextLink) as QueryOperationResponse&lt;User&gt;; }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多