I am using HotChocolate (11.2.2) with EF Core and want to filter a sub property. According to the GraphQL docu this should be possible by using the filter keyword on the navigation property but HotChocolate just fails.
My schema:
type A {
Name: string,
RefTo: [B]
}
type B {
TypeName: string,
Value: int
}
This is backed by EF and I provide an IQueryable<A>
to HotChocolate.
[UsePaging]
[UseProjection]
[UseFiltering]
[UseSorting]
public IQueryable<A> GetAs([Service] Context db) => db.As.AsSingleQuery().AsNoTrackingWithIdentityResolution();
Now I want to include only those B
s where the TypeName
is equal to "ExampleType"
like this:
query {
As {
Name,
RefTo(where: { TypeName: { eq: "ExampleType" } })
{
TypeName,
Value
}
}
}
But HotChcolate does not seem to understand this and says:
Unknown argument "where" on field "A.RefTo".validation
Is it possible to filter Navigation Properties with an EF Core model?
You would have to add filtering to RefTo too
[UseFiltering]
public ICollection<A> RefTo {get; set;}
If you want to apply UseFiltering
, UseSorting
, etc. to all fields with result type ICollection
you can use a 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();
}
}
}
}
See my gist here: https://gist.github.com/zliebersbach/b7db2b2fcede98f220f55aa92276ad6e#file-filtercollectiontypeinterceptor-cs
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.