问题
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!
回答1:
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);
回答2:
You need to tell graphql dotnet how to map the Enum type to the EnumerationGraphType.
GraphTypeTypeRegistry.Register(typeof(MeetingStatusType), typeof(EnumerationGraphType<MeetingStatusType>));
来源:https://stackoverflow.com/questions/56032660/converting-net-enum-to-graphql-enumerationgraphtype