实现Types后GraphQL无法获取EF关联对象的报错问题
问题复现
发起如下GraphQL查询:
query{ platform{ id, name, commands{ howTo } } }
返回结果中platform字段数据正常,但commands值为null,同时抛出如下错误:
{ "message": "未在`commands`字段上找到名为`platform`的参数", "locations": [ { "line": 5, "column": 5 } ], "path": [ "platform", 1, "commands" ], "extensions": { "fieldName": "commands", "argumentName": "platform" } }
目前已知移除自定义Type配置后查询可正常运行,添加Type配置后无法正常获取关联对象。
解决方案
该问题由自定义类型的关联字段参数配置错误导致,可按以下步骤修复:
- 找到
PlatformType类型定义文件,检查commands字段的Resolver配置:
关联父级对象的Resolver方法,第一个参数必须标注[Parent]属性从父级上下文获取Platform数据,不需要额外声明platform查询参数,正确写法参考:// PlatformType字段配置 Field(p => p.Commands) .ResolveWith<CommandResolvers>(r => r.GetCommands(default!, default!)) .UseDbContext<AppDbContext>(); // Resolver方法实现 public IQueryable<Command> GetCommands([Parent] Platform platform, [ScopedService] AppDbContext dbContext) { return dbContext.Commands.Where(c => c.PlatformId == platform.Id); } - 检查
commands字段配置是否误加了多余的Argument声明,若有直接移除即可,关联父级数据不需要在查询时显式传参。 - 如果使用注解方式定义类型,检查
Platform类的Commands属性上是否错误添加了参数相关的注解,删除多余注解后重启服务即可。
内容的提问来源于stack exchange,提问作者Dikesh Kumar
相关产品推荐
相关产品推荐

