C# Azure Functions集成GraphQL时Query、Mutation找不到包及命名空间报错问询
问题根因
你遇到的报错本质是没有自行实现Query和Mutation对应的C#业务类,这两个类不是GraphQL框架的内置类,需要你自己根据Schema定义的字段编写对应的 resolver 逻辑,所以IntelliSense才会错误推荐Entity Framework的无关Query类。
修复步骤
1. 自行实现Query和Mutation类
在你的项目中新增两个类,对应Schema中定义的查询和变更逻辑,示例代码如下:
// Query类示例 public class Query { // 对应Schema中Query的users字段,返回用户列表 public List<User> GetUsers([Service] IUserRepository userRepo) { return userRepo.GetAllUsers().ToList(); } // 对应Schema中Query的user(id)字段,返回单用户 public User GetUserById(Guid id, [Service] IUserRepository userRepo) { return userRepo.GetUserById(id); } } // Mutation类示例 public class Mutation { // 对应Schema中Mutation的createUser字段 public User CreateUser(UserInput input, [Service] IUserRepository userRepo) { return userRepo.AddUser(input); } // 其余updateUser、deleteUser方法同理实现 public User UpdateUser(UserInput input, [Service] IUserRepository userRepo) => userRepo.UpdateUser(input); public string DeleteUser(Guid id, [Service] IUserRepository userRepo) => userRepo.DeleteUser(id) ? "删除成功" : "删除失败"; }
注意如果这两个类和你的Schema定义类不在同一个命名空间,需要手动using对应的命名空间,即可解决找不到类的报错。
2. 修正现有Schema的错误定义
你当前写的Schema存在多处语法/类型错误,也会导致后续运行报错:
- 内置标量类型错误:GraphQL官方内置标量为
ID、String、Boolean,你写的string、bool、GUID都不合法,GUID可以直接用ID类型代替,Date需要你额外引入自定义标量包或者先暂用String类型传时间字符串 - 类型重名冲突:你同时定义了
type User和input User,名称不能重复,input类型需要改名为UserInput - 类型大小写错误:
Squad类型你写为小写的squad,需要和C#类名保持一致,同时你需要补充Squad类型的Schema定义 - 读写操作位置错误:
getUsers、getUserById是读操作,应该放在Query下,不要放在Mutation里
修正后的Schema示例:
type User { Id: ID Name: String Email: String AdminUser: Boolean Birthday: String DietaryRequirements: [String] InformationRequired: Boolean Squad: Squad } type Squad { # 这里补全Squad类对应的字段 Id: ID Name: String } input UserInput { Id: ID Name: String Email: String AdminUser: Boolean Birthday: String DietaryRequirements: [String] InformationRequired: Boolean Squad: SquadInput } input SquadInput { Id: ID } type Mutation { createUser(input: UserInput) : User updateUser(input: UserInput) : User deleteUser(id: ID) : String } type Query { users: [User] user(id: ID) : User }
3. 检查依赖包安装
确保你已经安装了所需的NuGet包:
GraphQLGraphQL.Server.Core(对应Azure Functions场景的版本即可)- 如果用到自定义标量需要额外安装
GraphQL.SystemTextJson等相关依赖包
内容的提问来源于stack exchange,提问作者Yohan
相关产品推荐
相关产品推荐

