将.NET枚举转换为GraphQL EnumerationGraphType

问题描述:

如何将枚举转换为GraphQL使用的EnumerationGraphType?
下面是一个示例来说明我在说什么:

How do I convert an enum to the EnumerationGraphType that GraphQL uses? Here is an example to illustrate what I'm talking about:

public enum MeetingStatusType
{
    Tentative,
    Unconfirmed,
    Confirmed,
}



public class MeetingDto
{
    public string Id { get; set; }
    public string Name { get; set; }
    public MeetingStatusType Status { get; set; }
}



public class MeetingStatusEnumType : EnumerationGraphType<MeetingStatusType>
{
    public MeetingStatusEnumType()
    {
        Name = "MeetingStatusType";
    }
}



public class MeetingType : ObjectGraphType<MeetingDto>
{
    public MeetingType()
    {
        Field(m => m.Id);
        Field(m => m.Name, nullable: true);
        Field<MeetingStatusEnumType>(m => m.Status); // Fails here
     }
}

显然,这是行不通的,因为从 MeetingStatusType MeetingStatusEnumType 没有隐式转换。 在文档中,他们正在映射的模型将依赖直接在 MeetingStatusEnumType 上,但是在域类型和对象等内容上引入对GraphQL的依赖似乎并不好。
我觉得我错过了一种非常简单的方法来注册该字段,但我一生都无法解决。

Obviously this doesn't work because there's no implicit conversion from MeetingStatusType to MeetingStatusEnumType. In the documentation, the models that they were mapping would rely directly on MeetingStatusEnumType, but it doesn't seem good to introduce the dependency on GraphQL on something like your domain types and objects. I feel like I'm missing a painfully easy way to register this field, but I can't figure it out for the life of me. Any help would be greatly appreciated!

看起来我不应该尝试使用表达式重载来映射字段。将其切换为以下内容似乎已解决了该问题:

Looks like I should not have been trying to use the expression overload for mapping the fields. Switching it out to be the following instead seems to have solved the issue:

Field(e => e.Id);
Field(e => e.Name, nullable: true);
Field<MeetingStatusEnumType>("meetingStatus", resolve: e => e.Source.Status);