0

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

2
  • What is Station? If it's a related entity shouldn't you use ` context.Readings.Include(rd=>rd.Station)` ? Commented Oct 4, 2022 at 12:00
  • That seems to have solved the issue so apparently yes 👍 Commented Oct 4, 2022 at 12:05

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.