使用 Simple.Odata.Client 将 Batch GET 请求结果添加到列表
Adding Batch GET request results to a list using Simple.Odata.Client
使用 Simple.Odata.Client,我正在批处理 GET 请求并将这些请求的结果添加到列表中。如下图:
var results = new List<Thing>();
var ids = new List<long>() { 1, 2, 3, 4, 5, 6 };
var batch = new ODataBatch(_client);
foreach (var id in ids)
{
batch += async c =>
{
results.Add(await c.For<Thing>().Key(id).FindEntryAsync());
};
}
await batch.ExecuteAsync();
问题在于(如此处所述 - https://github.com/simple-odata-client/Simple.OData.Client/issues/181)批处理程序被调用两次,这意味着对于添加到结果列表的每个成功结果,也会添加一个空值。
据说解决方案是 "move all statements not related to batch operations (like results.Add(...)) out of the batch lambda." 但是我不明白该怎么做,因为我无法访问 lambda 之外的批处理请求的结果。我知道解决方案是在将结果添加到结果列表之前检查是否为空,但我想看看是否有人知道更好的方法,或者可以解释如何在批处理 lambda 之外添加结果。谢谢:)
在这里回答我自己的问题。因为批处理程序被调用了两次,所以我找到的唯一真正的解决方案是将查询结果分配给批处理 lambda 中的局部变量,然后仅当结果不为 null 时才将该结果添加到结果列表中。
这是一个例子:
var results = new List<Thing>();
var ids = new List<long>() { 1, 2, 3, 4, 5, 6 };
var batch = new ODataBatch(_client);
foreach (var id in ids)
{
batch += async c =>
{
Thing result;
result = await c.For<Thing>().Key(id).FindEntryAsync();
if (result != null) {
results.Add(result);
}
};
}
await batch.ExecuteAsync();
使用 Simple.Odata.Client,我正在批处理 GET 请求并将这些请求的结果添加到列表中。如下图:
var results = new List<Thing>();
var ids = new List<long>() { 1, 2, 3, 4, 5, 6 };
var batch = new ODataBatch(_client);
foreach (var id in ids)
{
batch += async c =>
{
results.Add(await c.For<Thing>().Key(id).FindEntryAsync());
};
}
await batch.ExecuteAsync();
问题在于(如此处所述 - https://github.com/simple-odata-client/Simple.OData.Client/issues/181)批处理程序被调用两次,这意味着对于添加到结果列表的每个成功结果,也会添加一个空值。
据说解决方案是 "move all statements not related to batch operations (like results.Add(...)) out of the batch lambda." 但是我不明白该怎么做,因为我无法访问 lambda 之外的批处理请求的结果。我知道解决方案是在将结果添加到结果列表之前检查是否为空,但我想看看是否有人知道更好的方法,或者可以解释如何在批处理 lambda 之外添加结果。谢谢:)
在这里回答我自己的问题。因为批处理程序被调用了两次,所以我找到的唯一真正的解决方案是将查询结果分配给批处理 lambda 中的局部变量,然后仅当结果不为 null 时才将该结果添加到结果列表中。
这是一个例子:
var results = new List<Thing>();
var ids = new List<long>() { 1, 2, 3, 4, 5, 6 };
var batch = new ODataBatch(_client);
foreach (var id in ids)
{
batch += async c =>
{
Thing result;
result = await c.For<Thing>().Key(id).FindEntryAsync();
if (result != null) {
results.Add(result);
}
};
}
await batch.ExecuteAsync();