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
       }
    }
  }
}