ASP.NET Core中使用GraphQL - 目錄
- ASP.NET Core中使用GraphQL - 第一章 Hello World
- ASP.NET Core中使用GraphQL - 第二章 中間件
- ASP.NET Core中使用GraphQL - 第三章 依賴注入
- ASP.NET Core中使用GraphQL - 第四章 GrahpiQL
- ASP.NET Core中使用GraphQL - 第五章 字段, 參數, 變量
- ASP.NET Core中使用GraphQL - 第六章 使用EF Core作為持久化倉儲
在前面幾篇中,我們已經介紹了如何使用GraphQL中的query
字段獲取數據。那么如何使用GraphQL進行數據的添加,刪除,修改操作呢?這里我們需要引入GraphQL中的mutation
。
我們繼續編寫新代碼之前,我們需要先整理一下當前的項目代碼。這里我們將HelloWorldQuery
類改名為InventoryQuery
類, 並將HelloWorldSchema
類改名為InventorySchema
。然后我們將hello
和howdy
兩個字段移除掉。
在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
字段返回一個對象類型,你就可以查詢它的內嵌字段。這對於獲取一個更新后對象的新狀態非常有用。
在我們運行程序之前,我們還如要在控制反轉容器中注冊ItemInputType
和InventoryMutation
。
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
}
}
這段代碼的意思是,我們將調用createItem
的mutation
, 將item保存到數據庫,並會返回新增item的title
和barcode
屬性。
當然你也可以把添加的item對象放到Query Variables
窗口中, 得到的結果是一樣的
本文源代碼: https://github.com/lamondlu/GraphQL_Blogs/tree/master/Part%20VII