【发布时间】:2021-06-03 18:12:35
【问题描述】:
在查询类型中使用带有 UseFiltering() 方法的解析器时遇到问题。
目前,我正在为查询类型的所有字段使用解析器。我不知道这是否是最佳做法。我将说明临时代码。
public class QueryType {
// nothing here just a empty class
}
public class QueryTypeWithFieldResolvers : ObjectType<QueryType>
{
protected override void Configure(IObjectTypeDescriptor<QueryType> descriptor)
{
base.Configure(descriptor);
descriptor.Field(nameof(GenericResolvers<User>.Get))
.Name("get")
.Type<ListType<ObjectType<User>>>()
.ResolveWith<GenericResolvers<User>>(r => r.Get(default!));
descriptor.Field(nameof(GenericResolvers<User>.GetById))
.Name("getById")
.Argument("id", argsDescriptor => argsDescriptor.Type<StringType>()
.Type<ObjectType<User>>()
.ResolveWith<GenericResolvers<User>>(r => r.GetById(default!, default!));
}
}
上面的一切仍然正常工作。直到我想添加 Filtering 并使用这种方法对查询类型中名为 "filter" 的新字段使用 Resolver。
过滤中间件似乎没有按预期工作,它返回了数据库中的所有数据。
public class QueryTypeWithFieldResolvers : ObjectType<QueryType>
{
protected override void Configure(IObjectTypeDescriptor<QueryType> descriptor)
{
// omitted
...
descriptor.Field(nameof(GenericResolvers<User>.Filter))
.Name("filter")
.Type<ListType<ObjectType<User>>>>()
.ResolveWith<GenericResolvers<User>>(r => r.Filter(default!))
.UseFiltering<UserFilterInputType>();
}
}
更新以将字段 "filter" 声明为 QueryType 类中的方法
使用这种方法,它可以按照Hotchocolate Filtering 的说明进行操作
public class QueryType {
public IQueryable<User> Filter([Service] IGenericRepository<User> repo)
{
return repo.Query();
}
}
public class QueryTypeWithFieldResolvers : ObjectType<QueryType>
{
protected override void Configure(IObjectTypeDescriptor<QueryType> descriptor)
{
// omitted
...
// updated to use field expression directly
descriptor.Field(f => f.Filter(default!))
.Type<ListType<ObjectType<User>>>()
.UseFiltering();
}
}
据我所知,它们都是 HotChocolate 的有效代码优先方法,但我不知道上述两种方法之间有什么区别。所以请帮我解释一下为什么?提前致谢。
【问题讨论】:
标签: c# asp.net-core graphql hotchocolate