如何将 DTO 的 ODataQueryOptions 应用于底层 EntitySet?

How to apply ODataQueryOptions for DTO to underlying EntitySet?

有 2 个 类,Foo 和 Bar。在 Foo 对象中嵌套了一个 Bar 对象。

public class Foo {
    public Guid FooId { get; set; }
    public string FooName { get; set; }
    [ForeignKey("Bar")]
    public Guid BarId { get; set; }

    public virtual Bar Bar { get; set; }
}

public class Bar {
    public Guid BarId { get; set; }
    public string BarName { get; set; }
}

public class FooBarContext : DbContext {
    public DbSet<Foo> Foos { get; set; }
    public DbSet<Bar> Bars { get; set; }
}

public class FooDTO {
    public Guid FooId { get; set; }
    public string FooName { get; set; }
    public Guid BarId { get; set; }
    public string BarName { get; set; }
}

我的问题是:我能否以某种方式将 FooDTO 的 OData 查询转换为 Foo 的 OData 查询,以便它可以应用于 Foos DbSet?

比如我想通过BarName来查询,最终是嵌套的Bar对象。

GET /Foos?$filter=BarName eq 'Bar2'

这是处理查询的控制器和操作

public class FoosController {
    public async Task<IHttpActionResult> GetFoos(ODataQueryOptions<FooDTO> queryOptions) {
        // translate filter FooDTO.BarName to filter Foo.Bar.Name
        // ODataQueryOptions<Foo> fooQueryOptions = ....
        using (var context = new FooBarContext()) {
            return fooQueryOptions.ApplyTo(context.Foos);
        }
    }
}

谢谢。

首先将 OData 包安装到您的 Web API 项目

Install-Package Microsoft.AspNet.OData -Version 7.1.0

通过添加以下 using 语句

WebApiConfig.cs 中配置 OData 端点
using System.Web.OData.Builder;
using System.Web.OData.Extensions;

以及 Register 方法的以下代码

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

    // New code start
    ODataModelBuilder builder = new ODataConventionModelBuilder();
    builder.EntitySet<Foo>("Foos");
    builder.EntitySet<Bar>("Bars");
    config.MapODataServiceRoute(
        routeName: "ODataRoute",
        routePrefix: null,
        model: builder.GetEdmModel());

    config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);

    config.EnableDependencyInjection();
    // New code end

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

映射更新:在您的控制器中

[EnableQuery()] // Enables clients to modify the query, by using query options such as $filter, $sort, and $page
public async Task<IHttpActionResult> GetFoos(ODataQueryOptions<FooDTO> queryOptions)
{
    using (var context = new FooBarContext())
    {
        return queryOptions.ApplyTo(context.Foos.AsQueryable().Select(f => new FooDTO
        {
            BarId = f.BarId,
            BarName = f.Bar.BarName,
            FooId = f.FooId,
            FooName = f.FooName
        }));
    }
}

更多检查Create an OData v4 Endpoint Using ASP.NET Web API

还有 Supercharging your Web APIs with OData and ASP.NET Core(对于 .Net 核心,但它可能有帮助)