Hotchocolate, 转 on/off 按类型中的字段排序

Hotchocolate, turn on/off sorting by field in a type

我使用 IQueryable 公开我的 'Example' class 并应用 [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' class 具有三个属性,我只希望用户可以订购其中的两个。用户在第三个 属性 之前订购是没有意义的。如何指定要从排序中间件中排除的 'Example' 的属性之一?

假设,您有 Prop1、Prop2 和 Prop3,并且只想允许对 Prop1 和 Prop2 进行排序。为此,您只需按以下方式实现 "sorting metadata" 类型:

 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)...