ASP.NET Core中使用GraphQL - 第七章 Mutation

ASP.NET Core中使用GraphQL - 目录


在前面几篇中,我们已经介绍了如何使用GraphQL中的query字段获取数据。那么如何使用GraphQL进行数据的添加,删除,修改操作呢?这里我们需要引入GraphQL中的mutation

我们继续编写新代码之前,我们需要先整理一下当前的项目代码。这里我们将HelloWorldQuery类改名为InventoryQuery类, 并将HelloWorldSchema类改名为InventorySchema。然后我们将hellohowdy两个字段移除掉。

在GraphQL中, 一个Mutation类型也是继承自ObjectGraphType类。在以下代码中,createItem字段在服务器端创建了一个货物并返回了它的内容。

InventoryMutation
public class InventoryMutation : ObjectGraphType  
{
    public InventoryMutation(IDataStore dataStore)
    {         
        Field<ItemType>(
            "createItem",
            arguments: new QueryArguments(
                new QueryArgument<NonNullGraphType<ItemInputType>> { Name = "item" }
            ),
            resolve: context =>
            {
                var item = context.GetArgument<Item>("item");
                return dataStore.AddItem(item);
            });
    }
}

以上代码中我们引入了一个新的ItemInputType类作为查询参数。在第五章中,我们已经创建过一个标量类型的参数。但是针对复杂类型,我们使用不同的方式。因此,这里我们创建了一个新的类ItemInputType。其代码如下:

ItemInputType
public class ItemInputType : InputObjectGraphType  
{
    public ItemInputType()
    {
        Name = "ItemInput";
        Field<NonNullGraphType<StringGraphType>>("barcode");
        Field<NonNullGraphType<StringGraphType>>("title");
        Field<NonNullGraphType<DecimalGraphType>>("sellingPrice");
    }
}

为了将新的货物记录添加到数据库,我们还需要修改IDataStore接口,添加一个AddItem的方法,并在DataStore类中实现它。

IDataStore
public interface IDataStore
{
	IEnumerable<Item> GetItems();
	Item GetItemByBarcode(string barcode);
	Task<Item> AddItem(Item item);
}
DataStore
public async Task<Item> AddItem(Item item)  
{
    var addedItem = await _context.Items.AddAsync(item);
    await _context.SaveChangesAsync();
    return addedItem.Entity;
}

这里请注意AddItem的方法签名,在添加完成之后,我们将添加成功的货物记录返回了。因此我们可以查询新添加对象的内嵌字段

Just like in queries, if the mutation field returns an object type, you can ask for nested fields. This can be useful for fetching the new state of an object after an update. - GraphQl Org.

和查询一样,如果mutation字段返回一个对象类型,你就可以查询它的内嵌字段。这对于获取一个更新后对象的新状态非常有用。

在我们运行程序之前,我们还如要在控制反转容器中注册ItemInputTypeInventoryMutation

Startup
services.AddScoped<ItemInputType>();  
services.AddScoped<InventoryMutation>();  

最后我们需要在InventorySchema的构造函数中,注入InventoryMutation

InventorySchame
public class InventorySchema : Schema  
{
    public InventorySchema(InventoryQuery query, InventoryMutation mutation)
    {
        Query = query;
        Mutation = mutation;
    }
}

现在你可以运行程序了,这里我们运行如下的mutation

mutation {  
  createItem(item: {title: "GPU", barcode: "112", sellingPrice: 100}) {
    title
    barcode
  }
}

这段代码的意思是,我们将调用createItemmutation, 将item保存到数据库,并会返回新增item的titlebarcode属性。

当然你也可以把添加的item对象放到Query Variables窗口中, 得到的结果是一样的

本文源代码: https://github.com/lamondlu/GraphQL_Blogs/tree/master/Part%20VII

posted @   LamondLu  阅读(2290)  评论(5编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示
主题色彩