在 ASP.NET Core 中使用 GraphQL - Part 3
在 GraphQL 中,可以在查詢資料時,只選擇特定的欄位。但在前一篇文章中,可以看到像這樣的程式碼:resolve: context => companyRepository.GetAll()
,也就是說雖然傳回前端的資料只有部份欄位,但在後端中其實是撈出所有的欄位。這其實是可以解決的,像是下列程式碼:
public class AllDatas : ObjectGraphType
{
public AllDatas(IEmployeeRepository employeeRepository, ICompanyRepository companyRepository)
{
Name = "AllDatas";
Field<ListGraphType<EmployeeType>>(
"employees",
resolve: context => employeeRepository.GetSomeColumnsOfAll(new List<string> { "Name", "Age" })
);
Field<ListGraphType<CompanyType>>(
"companies",
resolve: context =>
{
var names = context.SubFields.Keys.ToList();
return companyRepository.GetSomeColumnsOfAll(names);
}
);
}
}
上面的程式碼,可以看到var names = context.SubFields.Keys.ToList();
這一行,就是取出前端傳過來的欄位有哪些,然後就可以將這些參數傳到 Repository 裡,至於底層要怎麼實作,就要看資料庫那端是用 Entity Framework 或是 Dapper,這部份之後會另外寫文章介紹,Dapper 的部份會比較簡單些,因為它吃的是純 SQL 指令。