首页 > 解决方案 > 输入类型对象可以包含接口类型的属性吗?

问题描述

我才开始在 .net 平台上学习 GraphQL。如果输入类型对象可以包含接口类型的属性,那么如何在 HotChocolate 库中配置它?

模型示例:

public interface ILocationFilter {
    double Lat { get; set;}
    double Lng { get; set;}
}

public class LocationFilter : ILocationFilter {
// ...
}

public class FilterModel {
    public string Search { get; set; }
    public ILocationFilter Location { get; set; } = new LocationFilter();
// ...
}

GraphQL 查询示例:

public class Query {
    public IEnumerable<SomeModel> GetByFilter(FilterModel filter) {
// ...
    }
}

Startup.cs 示例:

// ...
services.AddGraphQL(SchemaBuilder.New()
                        .AddQueryType<Query>()
                        .Create(),
                    new QueryExecutionOptions { IncludeExceptionDetails = true });
// ...
    app.UseGrapQL();
// ...

现在我得到一个异常“无法从类型引用 Input: ILocationFilter 推断或解析模式类型”。

顺便说一句:如果删除接口一切都会工作。

我应该配置什么来更正使用接口类型的属性?

标签: .netgraphqlhotchocolate

解决方案


public class FilterModelType : InputObjectType<FilterModel> {
    protected override void Configure(IInputObjectTypeDescriptor<FilterModel> descriptor)
    {
        descriptor.Field(x => x.Location).Type(typeof(LocationFilter));
    }
}

我添加了一个描述 FilterModel 的新类。之后我也在 Startup.cs 中注册了这个类型

 SchemaBuilder.New()
    .AddType<FilterModelType>()
    .AddQueryType<Query>()
    .Create() 

这个对我有用。


推荐阅读