gpt4 book ai didi

c# - 对 DTO 的 ASP.NET WebApi OData 支持

转载 作者:可可西里 更新时间:2023-11-01 08:11:30 24 4
gpt4 key购买 nike

我有项目实体和 ProjectDTO。我正在尝试创建一个 WebAPI Controller 方法,该方法可以获取和返回 ProjectDTO 并使其支持 OData。

问题是我使用的 ORM 可以使用项目实体而不是项目 DTO 查询数据库。有什么方法可以将基于 ProjectDTO 的 OData 的过滤/排序/分页应用于项目实体查询?

public ODataQueryResult<ProjectDTO> GetProjects(ODataQueryOptions<ProjectDTO> query)
{
var context = new ORM_Context();

var projects = context.Projects; // IQueryable<Project>
var projectDtos = query.ApplyTo(projectDTOs)); // <-- I want to achieve something similar here
var projectDTOs =
projects.Select(
x =>
new ProjectDTO
{
Id = x.Id,
Name = x.Name
});

var projectsQueriedList = projectDtos.ToList();

var result = new ODataQueryResult<ProjectDTO>(projectsQueriedList, totalCount);

return result;
}

最佳答案

类似的东西(我还没有尝试编译它)

using(var dataContext = new ORM_Context())
{
var projects = dataContext.Projects; // IQueryable<Project>

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

var t = new ODataValidationSettings() { MaxTop = 25 };
var s = new ODataQuerySettings() { PageSize = 25 };
newOptions.Validate(t);
IEnumerable<Project> internalResults =
(IEnumerable<Project>)newOptions.ApplyTo(projects, s);

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

var projectDTOs =
internalResults.Skip(skip).Take(take).Select(x =>
new ProjectDTO
{
Id = x.Id,
Name = x.Name
});

var projectsQueriedList = projectDtos.ToList();
var result = new ODataQueryResult<ProjectDTO>(
projectsQueriedList, totalCount);
return result;
}

关于c# - 对 DTO 的 ASP.NET WebApi OData 支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16962081/

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