【问题标题】:Hotchocolate, turn on/off sorting by field in a typeHotchocolate,打开/关闭按类型中的字段排序
【发布时间】:2020-05-22 11:34:18
【问题描述】:

我使用IQueryable 公开我的“示例”类并应用[UseSorting] 属性,以便用户可以定义结果的排序顺序。这很好用,而且 Playground 允许我这样做。

public class QueryType : ObjectType
{
    [UseSorting]
    public IQueryable<Example> GetExamples([Service]IExampleRepository repository)
    {
        return repository.GetExamples();
    }
}

public class ExampleType : ObjectType<Example>
{
    protected override void Configure(IObjectTypeDescriptor<Example> descriptor)
    {
    }
}

但是“Example”类有三个属性,我只希望用户可以订购其中的两个。用户按第三个属性订购是没有意义的。如何指定要从排序中间件中排除的“示例”属性之一?

【问题讨论】:

    标签: sorting graphql hotchocolate


    【解决方案1】:

    假设,您有 Prop1、Prop2 和 Prop3,并且希望只允许对 Prop1 和 Prop2 进行排序。为此,您只需按以下方式实现“排序元数据”类型:

     public class ExampleSortType : SortInputType<Example>
    {
        protected override void Configure(ISortInputTypeDescriptor<Example> descriptor)
        {
            ISortInputTypeDescriptor<Example> sortInputTypeDescriptor = descriptor.BindFieldsExplicitly();
    
            sortInputTypeDescriptor.Sortable(d => d.Prop1);
            sortInputTypeDescriptor.Sortable(d => d.Prop2);
        }
    }
    

    并为该元数据类型提供 UseSorting 属性:

    [UseSorting(SortType = typeof(ExampleSortType))]
     public IQueryable<Example> GetExamples([Service]IExampleRepository repository)...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-14
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 2013-11-03
      相关资源
      最近更新 更多