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

Viewed 1751

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?

1 Answers

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

Related