[英]Using projections without returning IQueryable, GraphQL HotChocolate
如果我不希望我的服務返回 IQueryable,有沒有辦法使用預測?
我正在考慮類似的事情,我的解析器可以將 map 輸入到表達式,然后調用服務 class,然后根據提供的表達式構建和執行查詢,轉換為一些只讀集合並返回給用戶。
類似於以下內容:
public async Task<IReadOnlyList<TestPayload>> GetAllTests(
[Service] ITestService,
CancellationToken cancellationToken,
object[] requestedFields) =>
await service.GetAllAsync(requestedFields, cancellationToken);
然后在我的服務中:
var expression = BuildExpression(requestedFields);
var output = testRepository.Queryable()
.Select(expression)
.AsNoTracking();
return output.ToListAsync();
你能給我指出一些關於這個的方向嗎?
編輯:
根據@Pascal 的回答,我添加了 HotChocolate.Data package 並在我的 IQueryable 上調用了 Project(context) 擴展方法。
現在我的有效載荷(模型)類有問題,但我不太清楚為什么。
以下示例將返回所有列並且不會應用投影。
[UseProjection]
public async Task<IReadOnlyList<TestPayload>> TestGetAll([Service] ITestService testService, IResolverContext context, CancellationToken cancellationToken)
{
return await testService.GetAllAsync(context, cancellationToken);
}
這將起作用,並將投射到查詢並僅返回所請求的內容。 請注意,唯一不同的是返回類型(IReadOnly 而不是 IReadOnly)。
[UseProjection]
public async Task<IReadOnlyList<Test>> TestGetAll([Service] ITestService testService, IResolverContext context, CancellationToken cancellationToken)
{
return await testService.GetAllAsync(context, cancellationToken);
}
服務內部:
var tests = testRepository.Queryable()
.Project<Test>(context)
.AsNoTracking();
我猜這是因為解析器現在正在使用 dto TestPayload 類型,然后在服務內部嘗試投影到實體(測試)的 IQueryable,但我不確定如何克服它。
是的,HotChocolate.Data 在 IQueryable 之上提供了擴展方法
public async Task<IReadOnlyList<TestPayload>> GetAllTests(
[Service] ITestService,
CancellationToken cancellationToken,
IResolverContext context) =>
await service.GetAllAsync(context, cancellationToken);
var output = testRepository.Queryable()
.Project(context)
.AsNoTracking();
return output.ToListAsync();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.