.Net6 + GraphQL + MongoDb 实现Mutate添加数据
系列文章列表,点击展示/隐藏
正文
介绍
Query的部分我们讲完了,现在讲一下Mutate(就是操作增修删) 本节讲一下新增
正文
新建Requests文件夹
public record AddPostInput(string Title, string Author);
public record AddPostPayload(Post Post);
新建PostMutation.cs
public class PostMutation
{
public async Task<AddPostPayload> CreatePostAsync(
[Service] DbContext db,
AddPostInput input)
{
var entity = new Post()
{
Title = input.Title,
Abstraction = "this is an introduction post for graphql",
Content = "some random content for post 1",
Author = input.Author,
PublishedAt = DateTime.Now.AddDays(-2),
Link = "http://link-to-post-1.html",
Comments = new List<Comment>
{
new() { CreatedAt = DateTime.Now, Content = "test comment 03 for post 1", Name = "kindUser02" }
},
};
await db.Post.InsertOneAsync(entity);
return new AddPostPayload(entity);
}
}
修改Program
builder.Services
.AddGraphQLServer()
.AddQueryType<PostQuery>()
.AddMutationType<PostMutation>()
.AddMongoDbFiltering()
.AddMongoDbSorting()
.AddMongoDbProjections()
.AddMongoDbPagingProviders()
.SetPagingOptions(new PagingOptions
{
MaxPageSize = 50,
IncludeTotalCount = true
});
这时候我们去https://localhost:7145/graphql/
调用接口
mutation {
createPost(input: { title: "test ttt", author: "aaaaaaaa" }) {
post {
title
}
}
}
query testGetPost {
posts(where: {
title: { eq: "1 - introduction to graphql" }
}) {
id
title
comments {
name
}
}
}
结语
本系列主要将GraphQL的使用,示例项目不能应用于生产,后续发一些GraphQL库出来讲解生产中的实际应用
联系作者:加群:867095512 @MrChuJiu
分类:
GraphQL
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端