ZackR
ZackR

Reputation: 73

Am I misunderstanding Projections in HotChocolate?

I cant seem to get Projections with HotChocolate working for GraphQl. According to the documentation Projections should prevent over-requesting of data from the DB, and help connect data in related tables. As a simple example I set up the following:

public class Name
{
    [Key]
    public Guid Id { get; set; } = Guid.NewGuid();
    public string FirstName { get; set; }
    public string LastName { get; set; }
}


public class Queries
{
    [UseProjection]
    [UseDbContext(typeof(DbAccess))]
    public IQueryable<Name> GetNames([ScopedService] DbAccess db)
    {
        return db.Names;
    }
}

public class NameType : ObjectType<Name>
{ }

In Startup.ConfigureServices:

        services.AddGraphQLServer()
            .AddType<NameType>()
            .AddQueryType<Queries>()
            .AddProjections();

So with this set up and I run a Graphql query like : {names{firstName}}

I would expect the sql generated to be something like

SELECT `n`.`FirstName` FROM `Names` AS `n`

Instead though it does

SELECT `n`.`Id`, `n`.`FirstName`, `n`.`LastName` FROM `Names` AS `n`

Is there some obvious thing that I am missing?

Edit for versions:

NetCore 5.0
EfCore 5.0.12
HotChocolate 11.0.7
Pomelo.EntityFrameworkCore.MySql 5.0.3

Upvotes: 1

Views: 4055

Answers (1)

ZackR
ZackR

Reputation: 73

Turns out after much trial and error that I had the attribute tags in the wrong order should be:

public class Queries
{
  [UseDbContext(typeof(DbAccess))]
  [UseProjection]
  public IQueryable<Name> GetNames([ScopedService] DbAccess db)
  {
    return db.Names;
  }
}

Upvotes: 4

Related Questions