简体   繁体   English

在 c# 中使用 GraphQL.Net 时,如何访问 GraphQL 字段中的参数值?

[英]How do I access the argument values in GraphQL fields when using GraphQL.Net with c#?

Consider the following query;考虑以下查询;

query {
  droid(id: "123") {
    id
    name
  }
}

I can access the id query argument on the server when using GraphQL.net like this;像这样使用 GraphQL.net 时,我可以访问服务器上的 id 查询参数;

public class Droid
{
  public string Id { get; set; }
  public string Name { get; set; }
}

public class DroidType : ObjectGraphType
{
  public DroidType()
  {
    Field<NonNullGraphType<IdGraphType>>("id");
    Field<StringGraphType>("name");
  }
}

public class StarWarsQuery : ObjectGraphType
{
  private List<Droid> _droids = new List<Droid>
  {
    new Droid { Id = "123", Name = "R2-D2" }
  };

  public StarWarsQuery()
  {
    Field<DroidType>(
      "droid",
      arguments: new QueryArguments(
        new QueryArgument<IdGraphType> { Name = "id" }
      ),
      resolve: context =>
      {
        var id = context.GetArgument<string>("id");//<---- THIS
        return _droids.FirstOrDefault(x => x.Id == id);
      }
    );
  }
}

But how would I handle a query like this;但是我将如何处理这样的查询;

query {
  droid(id: "123") {
    id
    name
    owner(id: "456") {
      id
      name
    }
  }
}

Its not a great example, but what I would expect would be to create an OwnerType and add a new field to my DriodType;这不是一个很好的例子,但我希望创建一个 OwnerType 并向我的 DriodType 添加一个新字段;

public class DroidType : ObjectGraphType
{
  public DroidType()
  {
    Field<NonNullGraphType<IdGraphType>>("id");
    Field<StringGraphType>("name");
    Field<OwnerType>(
      "owner",
      arguments: new QueryArguments(
        new QueryArgument<IdGraphType> { Name = "id" }
      ),
      resolve: context =>
      {
        var id = context.GetArgument<string>("id");
        return _owners.FirstOrDefault(x => x.Id == id);
      }
    );
  }
}

Here is my issue, I only want the owner with an ID of 456 if the driod with an ID of 123 has been owned by them.这是我的问题,如果 ID 为 123 的 drood 已被他们拥有,我只想要 ID 为 456 的所有者。 To do this I would need to filter the owners to only include those that had owned droid 123. To do that I need to be able to access the id of the droid from within the owner field of the DroidType ie I'd want to access the argument value of the droid field in StarWarsQuery from the owner field on the DroidType.为此,我需要过滤所有者以仅包含拥有 droid 123 的所有者。为此,我需要能够从 DroidType 的所有者字段中访问机器人的 id,即我想要访问StarWarsQuery 中 droid 字段的参数值来自 DroidType 上的 owner 字段。 How would I do this?我该怎么做?

The context in the resolve arguement for the owner field has a "Source" property, this holds information on the droid type.所有者字段的解析论证中的上下文有一个“源”属性,它包含有关机器人类型的信息。 I was able to get the information I needed from there我能够从那里获得我需要的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM