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

如何在GraphQL .NET中直接处理Dictionary类型?无需转换DTO

在.NET GraphQL中直接处理Dictionary<string, int>的最优方案

你不需要额外转换DTO或者手动转列表,有两种更直接的方案可以处理Dictionary<string, int>类型:

方案1:自定义字典GraphType,支持按Key查询值

这种方案适合需要通过指定Key获取对应Value的场景,更符合GraphQL按需获取数据的设计理念:

// 定义键值对类型,直接映射系统自带的KeyValuePair<string, int>
public class StringIntKeyValuePairType : ObjectGraphType<KeyValuePair<string, int>>
{
    public StringIntKeyValuePairType()
    {
        Field<StringGraphType>("key", resolve: ctx => ctx.Source.Key);
        Field<IntGraphType>("value", resolve: ctx => ctx.Source.Value);
    }
}

// 定义专门处理string-int字典的GraphType
public class StringIntDictionaryGraphType : ObjectGraphType<Dictionary<string, int>>
{
    public StringIntDictionaryGraphType()
    {
        Name = "StringIntDictionary";

        // 提供按key查询单个值的字段
        Field<IntGraphType>("getValue", 
            arguments: new QueryArguments(new QueryArgument<StringGraphType> { Name = "key" }),
            resolve: ctx => 
            {
                var dict = ctx.Source;
                var key = ctx.GetArgument<string>("key");
                return dict.TryGetValue(key, out var value) ? value : null;
            });

        // 提供返回所有键值对列表的字段
        Field<ListGraphType<StringIntKeyValuePairType>>("entries", 
            resolve: ctx => ctx.Source.ToList());
    }
}

在你的ExampleType中直接使用:

public class ExampleType : ObjectGraphType<ExampleDto>
{
    public ExampleType()
    {
        // 直接暴露字典类型
        Field<StringIntDictionaryGraphType>("myDictionary", resolve: ctx => ctx.Source.MyDictionary);
    }
}

查询示例:

query {
  example {
    myDictionary {
      getValue(key: "someKey")
      entries {
        key
        value
      }
    }
  }
}

方案2:直接返回键值对列表,无需自定义DTO

如果只需要返回所有键值对,不需要按Key查询,直接用系统的KeyValuePair<string, int>映射即可,省去自定义DTO的步骤:

public class ExampleType : ObjectGraphType<ExampleDto>
{
    public ExampleType()
    {
        Field<ListGraphType<StringIntKeyValuePairType>>(
            name: "myDictionaryEntries", 
            resolve: ctx => ctx.Source.MyDictionary.ToList()
        );
    }
}

这里的StringIntKeyValuePairType和方案1中的一致,直接复用即可。

为什么原来的方法需要转换?

GraphQL的类型系统基于对象和列表,而字典是键值对的集合,没有直接对应的GraphQL原生类型。通过自定义GraphType,我们可以把字典的结构转换成GraphQL能识别的类型,同时保留字典的特性(按Key查询)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 08:20:01