【问题标题】:Hot Chocolate: Transforming results from [UseFiltering] QueryHot Chocolate:转换 [UseFiltering] 查询的结果
【发布时间】:2022-01-04 22:27:52
【问题描述】:

我希望使用 Hot Chocolate 的过滤来查询一种数据类型;然后将该过滤后的输出转换为另一种类型,然后将其作为 IQueryable 返回。但我似乎无论如何都找不到捕获过滤器输入来开始我的转换。

这是我想要完成的一个示例:

给定数据类

public class TypeA
{
    public string Foo { get; set; }
}

public class TypeB
{
    public string Fizz { get; set; }
    public string Buzz { get; set; }
}

我希望能够创建类似的查询端点

public class Query
{
    [UseDbContext(typeof(DbContext))]
    [UseFiltering(typeof(TypeA))]
    public IQueryable<TypeB> GetTypeB(
        [ScopedService] DbContext context,
        [SomeAttributeToCaptureTheFilter] Filter filter) // <- this is the line I'm trying to figure out
    {
        IQueryable<TypeA> filteredTypeAs = context.TypeA.Filter(filter); // .Filter() doesn't exist, its just for example.
        IQueryable<TypeB> filteredTypeBs;
 
        /* Complex transformation logic that populates 'filteredTypeBs' 
         * requiring the 'filteredTypeAs' and additional Data from 
         * the database to complete. */

        return filteredTypeBs;
    }
}

对此,我可以使用如下所示的 GraphQL 查询

query {
  typeB(where: { foo: { eq: "bar" } }) {
    fizz
    buzz
  }
}

where: { foo: { eq: "bar" } } 作为TypeA 的过滤器,而

typeB {
  fizz
  buzz
} 

从转换后的TypeB 中提取内容。


使用[UseFiltering(typeof(TypeA))] 确实有效,它设置了架构以按照我的意愿行事。

我正在寻找的是 [SomeAttributeToCaptureTheFilter] Filter filter 行的效果。只是捕获过滤器并将其应用于 DbContext 中的数据的某种方式。

我还要说我对 GraphQL 很陌生,所以我处理这个问题的方式可能是完全错误的。任何建议都会有所帮助。

【问题讨论】:

  • 老实说,您遇到的需求看起来很奇怪。您能否提供您需要的真实示例(不是 foo bar baz)?

标签: c# entity-framework graphql hotchocolate


【解决方案1】:

为将来可能偶然发现此问题的任何人回答我自己的问题。

答案在HotChocolate.Data 包中。它包含Filter 扩展名IQueryable&lt;T&gt;IEnumberable&lt;T&gt;;这允许您通过传递IResolverContext 来内联运行过滤器。我在文档中找不到对此的任何引用,我在一个关于数据聚合的示例中遇到了它:https://github.com/ChilliCream/hotchocolate/issues/924#issuecomment-921793977

这基本上就是我的最终查询方法的样子:

using HotChocolate.Data;
using HotChocolate.Data.Filters.Expressions;

public class Query
{
    [UseDbContext(typeof(DbContext))]
    [UseFiltering(typeof(TypeA))]
    public IQueryable<TypeB> GetTypeB(
        [ScopedService] DbContext context,
        IResolverContext resolverContext)
    {
        IQueryable<TypeA> filteredTypeAs = context.TypeA.Filter(resolverContext);
        IQueryable<TypeB> filteredTypeBs;
 
        /* Complex transformation logic that populates 'filteredTypeBs' 
         * requiring the 'filteredTypeAs' and additional Data from 
         * the database to complete. */

        return filteredTypeBs;
    }
}

我知道我的示例有点深奥,但重点是它打开了对查询方法本身中结果的过滤版本的访问。当涉及到数据聚合/操作时,这为整个世界提供了可能性;同时仍然利用 HotChocolate 的内置功能。

附带说明,似乎还有一个 Sort 扩展名,相当于 [UseSorting]

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 2013-03-25
    相关资源
    最近更新 更多