Anil Narayan
Anil Narayan

Reputation: 31

"Derived" field resolver for GraphQL using Hot Chocolate and EFCore

I am working on a GraphQL endpoint using ASP.NET 5, Hot Chocolate and EFCore 5. I have entity framework entities that I'm exposing in GraphQL using Hot Chocolate. I have a need to "derive" one of the fields. Say for example I have a class called employee and it has FirstName and LastName properties. I want the GraphQL endpoint to expose a "FullName" field for the employee that will internally concatenate the first and last name. Note that FirstName and LastName values exist as columns of the Employee database table but the "FullName" field will be derived. How do I go about doing this? I attempted this as follows and it's not working

public class EmployeeType : ObjectType<Employee>
{
    protected override void Configure(IObjectTypeDescriptor<Employee> descriptor)
    {
        descriptor.Field(@"FullName")
            .Type<StringType>()
            .ResolveWith<Resolvers>( p => p.GetFullName(default!, default!) )
            .UseDbContext<AppDbContext>()
            .Description(@"Full name of the employee");
    }

    private class Resolvers
    {
        public string GetFullName(Employee e, [ScopedService] AppDbContext context)
        {
            return e.FirstName + " " + e.LastName;
        }
    }
}

The FullName field does show up in the GraphQL query but it is always blank. I think the Employee instance e that is passed into GetFullName() has empty string values for the first and last name.

How do I fix this? Is this the right approach to the problem?

Upvotes: 3

Views: 4032

Answers (2)

Babak
Babak

Reputation: 26

Currently the problem is that if your query doesn't have FirstName and LastName in the result, but only FullName is in the result, it returns empty. The reason is the returned emplyee object, doesn't have either FirstName nor lastName. To solve the issue: Decorate both FirstName and LastName with [IsProjected(true)]. This bring both of them behind the scenes to the query and FullName apears as you expect it.

Upvotes: 0

Tobias Tengler
Tobias Tengler

Reputation: 7454

Although I don't use ResolveWith myself often, I'm pretty sure you'd have to annotate the Employee using the ParentAttribute:

public string GetFullName([Parent] Employee e, [ScopedService] AppDbContext context)
{
    return e.FirstName + " " + e.LastName;
}

Learn more about this in the resolver documentation

Upvotes: 2

Related Questions