Home > Software engineering >  Nested objects in Dotnet GraphQL
Nested objects in Dotnet GraphQL

Time:10-05

I'm new to both Dotnet and GraphQl and I'm struggling with returning relational data from queries. I expect to be able to query nested data but receive null instead.

This is the query I'm using:

query {
  readings {
    level
    station {
      name
    }
  }
}

The expected output is:

{
    "level": 0.10000000149011612,
    "station": {
        "name": "example"
    }
}

but the actual output is:

{
    "level": 0.10000000149011612,
    "station": null
}

New readings are added like this:

[UseDbContext(typeof(AppDbContext))]
public async Task<AddReadingPayload> AddReadingAsync(
    AddReadingInput input,
    [ScopedService] AppDbContext context,
    CancellationToken cancellationToken
    )
{
    var Reading = new Reading
    {
        Station = context.Stations.FirstOrDefault((station) => station.Id == input.StationId),
        Level = input.Level
    };

    context.Readings.Add(Reading);
    await context.SaveChangesAsync(cancellationToken);
    return new AddReadingPayload(Reading);
}

and queried like this:

    [UseDbContext(typeof(AppDbContext))]
    public IQueryable<Reading> GetReadings([ScopedService] AppDbContext context)
    {
        return context.Readings;
    }

Since I'm new to this stuff I really have no idea where to look

CodePudding user response:

If Station is a related entity it needs to be eagerly loaded using Include :

[UseDbContext(typeof(AppDbContext))]
public IQueryable<Reading> GetReadings([ScopedService] AppDbContext context)
{
    return context.Readings.Include(r=>r.Station);
}

HotChocolate won't add this by default. Include by itself will result in a JOIN between the two tables which can result in a lot of repeated data from the "outer" table.

If you suspect that's a problem, you can use Split queries with AsSplitQuery() :

    return context.Readings
                  .Include(r=>r.Station)
                  .AsSplitQuery();
  • Related