gpt4 book ai didi

c# - 使用 WebApi 和映射模型实现 OData

转载 作者:太空狗 更新时间:2023-10-29 19:47:59 26 4
gpt4 key购买 nike

我正在尝试在 WebApi 中实现 OData。我使用的存储库模式和 EF5(在后端)仍然与我找到的所有示例一致。这就是事情变得不稳定的地方。我试图将 EF 生成的类隐藏在 Controller 中使用 AutoMapper 映射的模型后面。我看到的示例似乎返回了 repo 协议(protocol)中的任何内容

我不想在 Controller 中应用 OData 参数(到已映射的结果),而是在存储库中应用以保留延迟执行的值。我可以将 ODataCriteria 传递到存储库中,但是当我尝试 Appy 时,我收到一个错误,因为选项/结果似乎是从表示层而不是 IQueryable 键入到 IQueryable

我看到其他人在另一篇文章中避开了这一点,但是,这是该文章的一小部分,似乎没有帮助。

有没有其他人处理过这个?我真的不想公开 EF 类。哦,我先用DB。

提前致谢...

最佳答案

这里有一些代码可以证明您的要求。

要获得结果,您需要确保已执行查询(使用 ToList() )。最有效的方法是添加分页(奖励)并返回 PageResult<>对象。

public PageResult<WebPoco> Get(ODataQueryOptions<WebPoco> queryOptions)
{
var data2 = DatabaseData();

//Create a set of ODataQueryOptions for the internal class
ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<DatabasePoco>("DatabasePoco");
var context = new ODataQueryContext(
modelBuilder.GetEdmModel(), typeof(DatabasePoco));
var newOptions = new ODataQueryOptions<DatabasePoco>(context, Request);

var t = new ODataValidationSettings() { MaxTop = 25 };
var s = new ODataQuerySettings() { PageSize = 25 };
newOptions.Validate(t);
IEnumerable<DatabasePoco> results =
(IEnumerable<DatabasePoco>)newOptions.ApplyTo(data2, s);

int skip = newOptions.Skip == null ? 0 : newOptions.Skip.Value;
int take = newOptions.Top == null ? 25 : newOptions.Top.Value;

List<DatabasePoco> internalResults = results.Skip(skip).Take(take).ToList();

// map from DatabasePoco to WebPoco here:
List<WebPoco> webResults;

PageResult<WebPoco> page =
new PageResult<WebPoco>(
webResults, Request.GetNextPageLink(), Request.GetInlineCount());

return page;
}

这是using语句

using System.Web.Http;
using System.Web.Http.OData;
using System.Web.Http.OData.Builder;
using System.Web.Http.OData.Query;

测试类

public class WebPoco
{
public int id { get; set; }
public string name { get; set; }
public string type { get; set; }
}

public class DatabasePoco
{
public int id { get; set; }
public string name { get; set; }
public string type { get; set; }
}

和一些测试用的数据

private IQueryable<DatabasePoco> DatabaseData()
{
return (
new DatabasePoco[] {
new DatabasePoco() { id = 1, name = "one", type = "a" },
new DatabasePoco() { id = 2, name = "two", type = "b" },
new DatabasePoco() { id = 3, name = "three", type = "c" },
new DatabasePoco() { id = 4, name = "four", type = "d" },
new DatabasePoco() { id = 5, name = "five", type = "e" },
new DatabasePoco() { id = 6, name = "six", type = "f" },
new DatabasePoco() { id = 7, name = "seven", type = "g" },
new DatabasePoco() { id = 8, name = "eight", type = "h" },
new DatabasePoco() { id = 9, name = "nine", type = "i" }
})
.AsQueryable();
}

关于c# - 使用 WebApi 和映射模型实现 OData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16593115/

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