我有一个简单的枚举,我试图将其包含在我的GraphQL类型中,并收到以下错误:
无法隐式派生父类型“NewsItemType”上Field:“Category”的GraphQL类型。
-------------------无法隐式派生父类型“NewsItemType”上Field:“Category”的GraphQL类型。
- 类型:NewsType不能有效地强制为GraphQL类型参数名:type
我的简单枚举看起来像:
public enum NewsType
{
General = 0,
Business = 1,
Entertainment = 2,
Sports = 3,
Technology = 4
}
字符串
它包含在GraphQL ObjectGraphType
中:
public class NewsItemType : ObjectGraphType<NewsItemViewModel>
{
public NewsItemType()
{
Field(x => x.Id).Description("Id of a news item.");
Field(x => x.Title).Description("Title of a new item.");
Field(x => x.Description).Description("Description of a news item.");
Field(x => x.Author).Description("Author of a news item.");
Field(x => x.Url).Description("URI location of the news item");
Field(x => x.ImageUrl).Description("URI location of the image for the news item");
Field(x => x.PublishDate).Description("Date the news item was published");
Field(x => x.Category).Description("Category of the news item.");
}
}
型
最后是GraphQL类型所基于的视图模型:
public class NewsItemViewModel : ViewModelBase
{
public string Title { get; set; }
public string Author { get; set; }
public string Description { get; set; }
public string Url { get; set; }
public string ImageUrl { get; set; }
public DateTime PublishDate { get; set; }
public NewsType Category { get; set; }
}
型
我在这里做错了什么,我如何克服它?
编辑:我的查询包含以下内容:
Field<ListGraphType<NewsItemType>>(
name: "newsItems",
arguments: new QueryArguments(
new QueryArgument<IntGraphType>() { Name = "count" },
new QueryArgument<IntGraphType>() { Name = "category" }),
resolve: context =>
{
var count = context.GetArgument<int?>("count");
var category = context.GetArgument<int>("category");
var newsType = (NewsType)category;
if (count.HasValue)
{
return newsItemService.GetMostRecent(newsType, count.Value);
}
else
{
return newsItemService.GetMostRecent(newsType);
}
}
)
型
2条答案
按热度按时间4sup72z81#
我也很难让它工作。官方文档在这方面肯定是缺乏的。我让它工作的方式是基于我在this article中发现的东西。
对于您的场景,您将为枚举创建一个'GraphType'类,如下所示:
字符串
然后将您的字段更新为:
型
还有一件事要提到,我遇到了我没有预料到的EnumTypes。如果你使用枚举作为参数,请像上面那样将其作为
IntGraphType
摄取,然后将其转换为枚举类型(NewsType)category
型
我的枚举是作为参数传递的复杂对象的一部分,更像是
new QueryArgument<NewsItemType>() { Name = "newsItem" },
如果你要这样做,那么传递给服务器的对象的
category
属性需要是一个字符串。所以,如果你要传递回服务器的类别是Business = 1
,那么你需要传递category: 'Business'
而不是category: 1
。inn6fuwd2#
这里有一个快速的方法来完成这个任务。基本上你不使用默认的lambda表达式
Field
。而是实际上自己编写一个解析器并将枚举转换为正确的类型。这有助于GraphQL将类型正确转换为你想要返回的类型。字符串
如果你的枚举是一个字符串,你也可以这样做。
型
还有另一种更详细的方法,在这个答案中共享,首先从
EnumerationGraphType<T>
继承,然后执行与上面相同的自定义解析器。https://stackoverflow.com/a/56051133/11842628