1
// 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;
        }
    }
}

And when I call it's with graphql query with currency object.

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

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

Result currencyName is not null. And when I call it's without currency object.

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

And result currencyName is null. It is impossible include nested object like currency from code ? I want get currency Name without calling currency object in graphql query.

Abu Tolib
  • 13
  • 4

2 Answers2

1

No this is currently not possible as the property you access is only resolved if the nested class is selected

Pascal Senn
  • 1,712
  • 11
  • 20
  • Thanks :) Yes you're right for nested object IsProjected(true) and UseFirstOrDefault() if object is Collection not working. – Abu Tolib Feb 08 '22 at 08:19
0

It seems that you have projections enabled. In this case, you are not selecting the referenceid, and this is not being selected. as a consequence, your resolver is receiving 0 and cant resolve it correctly.

PhD
  • 1
  • 1