You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET GraphQL中FieldAsync方法的替代方案是什么?

解决GraphQL.NET 8.0.2中FieldAsync过时的异步查询实现方案

在GraphQL.NET 8.0.2版本中,FieldAsync方法已被标记为过时,官方推荐使用返回FieldBuilder的Field方法或直接调用AddField方法来实现异步查询。针对你的场景,有两种可行的替代方案:

方案一:使用Field方法链式配置异步Resolver

通过Field方法获取FieldBuilder,再调用ResolveAsync方法传入异步逻辑,这是最简洁的写法:

public class ExampleQuery : ObjectGraphType
{
    private readonly IExampleService _exampleService;

    public ExampleQuery(IExampleService exampleService)
    {
        _exampleService = exampleService;

        Field<ListGraphType<ExampleType>>("Examples")
            .ResolveAsync(async context =>
            {
                return await _exampleService.GetExamples();
            });
    }
}

方案二:直接使用AddField方法创建字段

手动构建FieldDefinition对象,指定字段名称、类型和异步Resolver,这种方式更灵活,适合需要自定义更多字段属性的场景:

public class ExampleQuery : ObjectGraphType
{
    private readonly IExampleService _exampleService;

    public ExampleQuery(IExampleService exampleService)
    {
        _exampleService = exampleService;

        AddField(new FieldDefinition
        {
            Name = "Examples",
            Type = typeof(ListGraphType<ExampleType>),
            Resolver = new AsyncFieldResolver<object, List<Example>>(async context =>
            {
                return await _exampleService.GetExamples();
            })
        });
    }
}

以上两种方式均符合GraphQL.NET 8.x的官方规范,能够完全替代原有的FieldAsync实现,同时消除CS0618和GQL004警告。

内容的提问来源于stack exchange,提问作者dede

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 00:59:58