微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

GraphQL 查询实现类属性但在模式中我只提到了接口如何?

如何解决GraphQL 查询实现类属性但在模式中我只提到了接口如何?

我已经声明了一个如下所示的模型类。

public class FunctionalOrganization : IOrganization
{
    public Guid Id { get; set; }
    public string LegalName { get; set; }
    public string Name { get; set; }
    public IAddress LegalAddress { get; set; }
}

IAddress 接口如下图

public interface IAddress : IModel
{
  string PrimaryLine { get; set; }
  string AdditionalLine { get; set; }
  string Country { get; set; }
}

IAddres 的实现(UnitedStatesAddress)(其中之一)如下

public class UnitedStatesAddress : IAddress
{
    public string PrimaryLine { get; set; }
    public string AdditionalLine { get; set; }
    public string Country { get; set; }
    public Guid Id { get; set; }
    public string City { get; set; }
    public string ZipCode { get; set; }
    public string State { get; set; }
}

如果我想查询 Graphql api 以从 IAddress 获取城市、邮编和州,它不会给出并显示错误

 query {
  organizationById (organizationId: "00000000-0000-0000-0000-000000000001"){
legalName
legalAddress {
  country
  primaryLine
  additionalLine
  state
}
id
registeredOn
asResponder {
   settings {
     isVisible
     dataCenterLocation
   }
}
  }
}

错误如下所示。

  {
  "errors": [
    {
      "message": "The field `state` does not exist on the type `Address`.","locations": [
        {
          "line": 8,"column": 7
        }
      ],"path": [
        "organizationById","legalAddress"
      ],"extensions": {
        "type": "Address","field": "state","responseName": "state","specifiedBy": "http://spec.graphql.org/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types"
      }
    }
  ]
}

有人能帮我解决这个问题吗?

解决方法

你必须在查询中选择接口的实现

 query {
  organizationById (organizationId: "00000000-0000-0000-0000-000000000001"){
     legalName
     legalAddress {
       country
      primaryLine
      additionalLine
      ... on UnitedStatesAddress {
         state
      }
    }
     id
     registeredOn
     asResponder {
       settings {
         isVisible
         dataCenterLocation
       }
    }
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。