.NET Core 6中GraphQL InputObjectGraphType及Mutation错误咨询
.NET Core 6 GraphQL Mutation 输入类型错误问题解答
错误核心原因
你在UserInputType中为contact字段指定了ObjectGraphType类型,而InputObjectGraphType(输入对象类型)只能包含输入类型字段:标量类型(ScalarGraphType)、枚举类型(EnumerationGraphType)或其他输入对象类型(IInputObjectGraphType)。ObjectGraphType是Query查询专用的输出类型,不能在输入类型中使用,这就是触发报错的根本原因。
疑问逐一解答
1. 操作错误点
UserInputType的contact字段误用了输出类型ObjectGraphType,违反了GraphQL输入类型的字段规则,直接导致ArgumentOutOfRangeException异常。
2. 需要创建单独的ContactInputType,定义及使用方式如下
必须为Contact模型创建对应的输入对象类型ContactInputType,继承自InputObjectGraphType(而非输出用的ObjectGraphType)。
定义ContactInputType
// 强类型绑定版本 public class ContactInputType : InputObjectGraphType<Contact> { public ContactInputType() { Field(x => x.firstName); Field(x => x.lastName); Field(x => x.email); Field(x => x.phoneNumber); } } // 无泛型版本(可选) public class ContactInputType : InputObjectGraphType { public ContactInputType() { Field<StringGraphType>("firstName"); Field<StringGraphType>("lastName"); Field<StringGraphType>("email"); Field<StringGraphType>("phoneNumber"); } }
在UserInputType中引入ContactInputType
修改UserInputType,将contact字段的类型替换为ContactInputType:
// 强类型绑定版本 public class UserInputType : InputObjectGraphType<User> { public UserInputType() { Field(x => x.id); Field(x => x.isActive); Field<ContactInputType>("contact"); // 使用输入类型而非输出类型 } } // 无泛型版本(可选) public class UserInputType : InputObjectGraphType { public UserInputType() { Field<StringGraphType>("id"); Field<BooleanGraphType>("isActive"); Field<ContactInputType>("contact"); } }
3. 单独传递字段无错误但contact为null的原因
单独传递四个标量字段时,所有字段都属于符合要求的标量输入类型,因此不会触发错误。但此时没有定义对应的contact输入对象结构,GraphQL无法将零散字段映射到User模型的contact属性上,所以contact显示为null,这是正常现象。
4. 解决方案总结
核心规则是嵌套对象必须对应单独的输入类型,确保输入对象类型的所有字段都属于输入类型范畴,禁止混用输出类型。
修正后的完整相关代码
ContactInputType.cs
public class ContactInputType : InputObjectGraphType<Contact> { public ContactInputType() { Field(x => x.firstName); Field(x => x.lastName); Field(x => x.email); Field(x => x.phoneNumber); } }
UserInputType.cs
public class UserInputType : InputObjectGraphType<User> { public UserInputType() { Field(x => x.id); Field(x => x.isActive); Field<ContactInputType>("contact"); } }
UserMutation.cs(无需修改)
public class UserMutation : ObjectGraphType { public UserMutation(IUser userService) { Field<UserType>("createUser", arguments: new QueryArguments( new QueryArgument<UserInputType> { Name = "user" } ), resolve: _ => userService.AddUser(_.GetArgument<User>("user")) ); } }
内容的提问来源于stack exchange,提问作者GThree
相关产品推荐
相关产品推荐

