Search code examples
c#.net-coregraphqlgraphql-dotnet

Converting .NET Enum to 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
     }
}

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!


Solution

  • 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);