ASP.NET Core中使用GraphQL - 目录html
在前面几篇中,咱们已经介绍了如何使用GraphQL中的query
字段获取数据。那么如何使用GraphQL进行数据的添加,删除,修改操做呢?这里咱们须要引入GraphQL中的mutation
。git
咱们继续编写新代码以前,咱们须要先整理一下当前的项目代码。这里咱们将HelloWorldQuery
类更名为InventoryQuery
类, 并将HelloWorldSchema
类更名为InventorySchema
。而后咱们将hello
和howdy
两个字段移除掉。github
在GraphQL中, 一个Mutation
类型也是继承自ObjectGraphType
类。在如下代码中,createItem
字段在服务器端建立了一个货物并返回了它的内容。数据库
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
。其代码以下:c#
public class ItemInputType : InputObjectGraphType { public ItemInputType() { Name = "ItemInput"; Field<NonNullGraphType<StringGraphType>>("barcode"); Field<NonNullGraphType<StringGraphType>>("title"); Field<NonNullGraphType<DecimalGraphType>>("sellingPrice"); } }
为了将新的货物记录添加到数据库,咱们还须要修改IDataStore
接口,添加一个AddItem
的方法,并在DataStore
类中实现它。服务器
public interface IDataStore { IEnumerable<Item> GetItems(); Item GetItemByBarcode(string barcode); Task<Item> AddItem(Item item); }
public async Task<Item> AddItem(Item item) { var addedItem = await _context.Items.AddAsync(item); await _context.SaveChangesAsync(); return addedItem.Entity; }
这里请注意AddItem
的方法签名,在添加完成以后,咱们将添加成功的货物记录返回了。所以咱们能够查询新添加对象的内嵌字段async
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
字段返回一个对象类型,你就能够查询它的内嵌字段。这对于获取一个更新后对象的新状态很是有用。fetch
在咱们运行程序以前,咱们还如要在控制反转容器中注册ItemInputType
和InventoryMutation
。3d
services.AddScoped<ItemInputType>(); services.AddScoped<InventoryMutation>();
最后咱们须要在InventorySchema
的构造函数中,注入InventoryMutation
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 } }
这段代码的意思是,咱们将调用createItem
的mutation
, 将item保存到数据库,并会返回新增item的title
和barcode
属性。
固然你也能够把添加的item对象放到Query Variables
窗口中, 获得的结果是同样的
本文源代码: https://github.com/lamondlu/GraphQL_Blogs/tree/master/Part%20VII