使用 Hot Chocolate 和 EFCore 的 GraphQL 的“派生”字段解析器

问题描述

我正在使用 ASP.NET 5、Hot Chocolate 和 EFCore 5 处理 GraphQL 端点。我使用 Hot Chocolate 在 GraphQL 中公开了实体框架实体。我需要“派生”其中一个领域。举例来说,我有一个名为employee 的类,它具有FirstName 和LastName 属性。我希望 GraphQL 端点为员工公开一个“全名”字段,该字段将在内部连接名字和姓氏。请注意,FirstName 和 LastName 值作为 Employee 数据库表的列存在,但将派生“FullName”字段。我该怎么做?我按如下方式尝试过,但它不起作用 -

    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;
            }
        }
    }

全名字段确实出现在 GraphQL 查询中,但它始终为空。我认为传递给 GetFullName() 的 Employee 实例 e 的名字和姓氏的字符串值为空。

我该如何解决这个问题?这是解决问题的正确方法吗?

解决方法

虽然我自己不经常使用 ResolveWith,但我很确定您必须使用 Employee 注释 ParentAttribute

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

Learn more about this in the resolver documentation