ASP.NET Core 5使用Hot Chocolate v5查询嵌套对象commands报错如何解决?
问题解决方法
错误原因
你在定义嵌套字段解析器时,没有给解析器方法的父对象参数添加Hot Chocolate的[Parent]特性,Hot Chocolate会默认将未标记特性的方法参数识别为该GraphQL字段的入参,因此会抛出找不到platform参数的错误。
单独查询platform/command不会触发嵌套字段的解析器逻辑,所以可以正常运行,只有嵌套查询时才会触发报错。
修复步骤
- 给解析器方法的父对象参数添加
[Parent]标记
首先修改PlatformType内部的解析器:
private class Resolvers { // 给Platform参数加[Parent]特性标记这是父级对象 public IQueryable<Command> GetCommands([Parent] Platform platform, [ScopedService] AppDbContext context) { return context.Commands.Where(p => p.PlatformId == platform.Id); } }
再修改CommandType内部的解析器,避免后续查询command下的platform字段时出现同类错误:
private class Resolvers { // 给Command参数加[Parent]特性标记这是父级对象 public Platform GetPlatform([Parent] Command command, [ScopedService] AppDbContext context) { return context.Platforms.FirstOrDefault(p => p.Id == command.PlatformId); } }
- (可选优化)使用投影避免手写解析器
你已经配置了EF Core的实体关联,可以直接给Query类的查询方法添加[UseProjection]特性,Hot Chocolate会自动处理关联字段的加载,不需要手动编写ResolveWith逻辑,还能自动避免N+1查询问题:
[UseDbContext(typeof(AppDbContext))] [UseFiltering] [UseSorting] [UseProjection] // 新增投影特性 [GraphQLDescription("Gets the queryable platform.")] public IQueryable<Platform> GetPlatform([ScopedService] AppDbContext context) { return context.Platforms; } [UseDbContext(typeof(AppDbContext))] [UseFiltering] [UseSorting] [UseProjection] // 新增投影特性 [GraphQLDescription("Gets the queryable command.")] public IQueryable<Command> GetCommand([ScopedService] AppDbContext context) { return context.Commands; }
添加后可以删除PlatformType、CommandType中关联字段的ResolveWith配置。
内容的提问来源于stack exchange,提问作者Wasyster
相关产品推荐
相关产品推荐

