簡體   English   中英

在 GraphQL HotChocolate 上篩選 EF Core Navigation 屬性

[英]Filter EF Core Navigation property on GraphQL HotChocolate

我將 HotChocolate (11.2.2) 與 EF Core 一起使用,並希望過濾子屬性。 根據 GraphQL 文檔,這應該可以通過在導航屬性上使用 filter 關鍵字來實現,但是 HotChocolate 只是失敗了。

我的模式:

type A {
    Name: string,
    RefTo: [B]
}
type B {
    TypeName: string,
    Value: int
}

這是由 EF 支持的,我向 HotChocolate 提供了一個IQueryable<A>

[UsePaging]
[UseProjection]
[UseFiltering]
[UseSorting]
public IQueryable<A> GetAs([Service] Context db) => db.As.AsSingleQuery().AsNoTrackingWithIdentityResolution();

現在我想只包含TypeName等於"ExampleType"的那些B ,如下所示:

query {
   As {
      Name,
      RefTo(where: { TypeName: { eq: "ExampleType" } })
      {
          TypeName,
          Value
      }
   }
}

但是 HotChcolate 似乎並不理解這一點並說:

Unknown argument "where" on field "A.RefTo".validation

是否可以使用 EF Core model 過濾導航屬性?

您也必須向 RefTo 添加過濾

    [UseFiltering] 
    public ICollection<A> RefTo {get; set;}

如果您想將UseFilteringUseSorting等應用於結果類型為ICollection的所有字段,您可以使用TypeInterceptor

using System;
using System.Collections.Generic;
using HotChocolate.Configuration;
using HotChocolate.Types;
using HotChocolate.Types.Descriptors;
using HotChocolate.Types.Descriptors.Definitions;

namespace MyApp
{
    public class FilterCollectionTypeInterceptor : TypeInterceptor
    {
        private static bool IsCollectionType(Type t)
            => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(ICollection<>);

        public override void OnBeforeRegisterDependencies(ITypeDiscoveryContext discoveryContext, DefinitionBase? definition,
            IDictionary<string, object?> contextData)
        {
            if (definition is not ObjectTypeDefinition objectTypeDefinition) return;
            
            for (var i = 0; i < objectTypeDefinition.Fields.Count; i++)
            {
                var field = objectTypeDefinition.Fields[i];
                if (field.ResultType is null || !IsCollectionType(field.ResultType)) continue;
                
                var descriptor = field.ToDescriptor(discoveryContext.DescriptorContext)
                    .UseFiltering()
                    .UseSorting();
                objectTypeDefinition.Fields[i] = descriptor.ToDefinition();
            }
        }
    }
}

在這里查看我的要點: https://gist.github.com/zliebersbach/b7db2b2fcede98f220f55aa92276ad6e#file-filtercollectiontypeinterceptor-cs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM