【问题标题】:HotChocolate (GraphQL) it is impossible include nested object without query callingHotChocolate (GraphQL) 在没有查询调用的情况下不可能包含嵌套对象
【发布时间】:2023-01-11 16:43:08
【问题描述】:
// Parent entity
public class Parent
{
   public int Id {get; set;}
   public int CurrencyId {get; set;}
   public virtual Currency Currency {get; set;}
}
// Currency Entity
public class Currency
{
  public int Id {get; set;}
  public string Name {get; set;}
  public virtual ICollection<Parent> Parents {get; set;}
}

// Query
[UseDbContext(typeof(AppDbContext))]
[UseFirstOrDefault]
[UseProjection]
[UseFiltering]
[UseSorting]
public IQueryable<Parent> GetParents([ScopedService] AppDbContext context, int id)
{
  return context.Set<Parent>().Where(x => x.id == id);
}

public class ParentType : ObjectType<Parent>
{
   protected override void Configure(IObjectTypeDescriptor<Parent> descriptor)
    {
        descriptor.Field("currencyName")
            .ResolveWith<Resolvers>(t => t.GetCurrencyName(default!));
    }

    private class Resolvers
    {
        public string GetCurrencyName([Parent] Parent parent)
        {
            return parent?.Currency?.Name;
        }
    }
}

当我用带货币对象的 graphql 查询调用它时。

    query{
     parents(id: 1){
      id
      currencyName
      currency{
       name
      }
     }
    }

//Result
{
  "data": {
    "parents": {
      "id": 1,
      "currency": {
        "name": "USD"
      },
      "currencyName": "USD"
    }
  }
}

结果 currencyName 不为空。当我调用它时没有货币对象。

       query{
         parents(id: 1){
          id
          currencyName
         }
        }
// Result
{
  "data": {
    "parents": {
      "Id": 1,
      "currencyName": null
    }
  }
}

结果 currencyName 为空。不可能从代码中包含像货币这样的嵌套对象? 我想在不调用 graphql 查询中的货币对象的情况下获取货币名称。

【问题讨论】:

    标签: c# graphql hotchocolate


    【解决方案1】:

    不,这目前是不可能的,因为您访问的属性只有在选择了嵌套类时才会解析

    【讨论】:

    • 谢谢 :) 是的,如果对象是 Collection 不起作用,那么您适合嵌套对象 IsProjected(true) 和 UseFirstOrDefault()。
    【解决方案2】:

    您似乎启用了投影。在这种情况下,您没有选择 referenceid,它也没有被选中。因此,您的解析器收到 0 并且无法正确解析它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多