gpt4 book ai didi

c# - 带有 Odata-V4 和 Dapper 的 Web Api - 服务器端过滤

转载 作者:行者123 更新时间:2023-11-30 16:04:07 26 4
gpt4 key购买 nike

我们使用带有 OData 和 Dapper 作为 ORM 的 ASP.Net Webapi。对于 GET 请求,我们分别使用选项参数对象和它的过滤器参数来为 Dapper 查询构建 SQL 字符串。这适用于列 eq 值等。

但现在我想做一些服务器端分页。这意味着我使用两个过滤器($top 和 $skip)发出请求。例如。 "https://api.server.com/Orders ?$skip=100&$top=50。Dapper 向数据库发出正确的请求,我得到一个包含 50 个条目的结果作为来自 dapper 的响应。

然后我将此结果放入 webapi Controller 的返回语句中,webapi 似乎自行进行过滤。因此它执行从 50 的结果中跳过 100,这导致 0 个条目。

有没有人遇到同样的问题并找到了一种方法来阻止 webapi 过滤但将过滤委托(delegate)给 ORM?编写 ApiControllers 而不是 ODataControllers 是别无选择,因为我真的很喜欢使用 odata 语法进行过滤。

感谢您的回答!

最佳答案

假设您的 API 操作的返回类型是 IQueryable,那么框架将对从数据库返回的任何数据应用查询过滤器,因此让我们将查询结果包装到 PageResult 中并返回它,它不会再次应用过滤器.示例代码如下-

public PageResult<Orders> GetOrdersPage(ODataQueryOptions<Orders> queryOptions)
{
// Parse queryOptions to get Top and Skip
var top = queryOptions.Top.RawValue;
var skip = queryOptions.Skip.RawValue;

//Call the dataaccess method and then get Querable result
var queryResults = dataAccess.GetOrders(top,skip).AsQuerable<Orders>();

//Return Page result
return new PageResult<Orders>(queryResults, new URI("Next page URI"), 1234); //1234 - is total count of records in table
}

关于c# - 带有 Odata-V4 和 Dapper 的 Web Api - 服务器端过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35696996/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com