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