我正在尝试在web API中实现GraphQL。当返回对象类型时,该方法工作正常。但是,当我试图返回对象列表时,它抛出了一个错误。
public class MyData
{
public int Code { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
Query.cs
public List<MyData> GetList()
{
List<MyData> myList = null;
string query = "select Code, Name, LastName, City, State, Country from MyTable";
using (var connection = new MySqlConnection(connectionString))
{
myList = connection.Query<MyData>(query).ToList();
}
return myList;
}
public class QueryObjectType : ObjectType<Query>
{
descriptor.Field(g => g.GetList())
.Type<MyDataDataObjectType>().Name("GetList");
}
public class MyDataDataObjectType: ObjectType<MyData>
{
protected override void Configure(IObjectTypeDescriptor<MyData> descriptor)
{
descriptor.Field(g => g.Code).Type<IntType>().Name("Code");
descriptor.Field(g => g.Name).Type<StringType>().Name("Name");
descriptor.Field(g => g.LastName).Type<StringType>().Name("LastName");
descriptor.Field(g => g.City).Type<StringType>().Name("City");
descriptor.Field(g => g.State).Type<IntType>().Name("State");
descriptor.Field(g => g.Country).Type<IntType>().Name("Country");
}
}
startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddGraphQLServer()
.AddQueryType<QueryObjectType>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseGraphQLVoyager(new VoyagerOptions()
{
GraphQLEndPoint = "/graphql"
}, "/graphql-ui");
}
GetList()方法返回具有MyData类型对象数据的列表。但在失眠客户端显示了一个错误。我认为下面的代码有问题
descriptor.Field(g => g.GetList())
.Type<MyDataDataObjectType>().Name("GetList");
我在POST调用中发送以下内容
query{
a:GetList
{
Code
}
}
错误:
{"errors"({消息": "意外执行错误","locations"({"line" 4"column" 4}],"path"("a","Code"],"extensions" {不能将父类强制转换为MyData。"stackTrace";在HotChocolate.Execution.Processing.MiddlewareContext。hotchocolate . execute . processing . middlewarecontext . SourceTrnrn在HotChocolate.Types.FieldMiddlewareCompiler.<>c__DisplayClass3_0.
d.MoveNext()rn——从前一个位置堆栈跟踪的结束——rn at hotchocolate . execute . processing . resolvertask。ExecuteResolverPipelineAsync(CancellationToken CancellationToken)rn在hotchocolate . execute . processing . resolvertask。TryExecuteAsync (CancellationToken CancellationToken)";}}],"data" {"a" {"Code"零}}}
提前感谢您的帮助。
您应该在服务器中看到一个异常,它会告诉您哪里出了问题。我可以看到的是,您指定的字段类型是错误的。当返回List时,您需要使用ListType
:
descriptor.Field(g => g.GetList())
.Type<ListType<MyDataDataObjectType>>().Name("GetList");
在列表文档
中了解更多信息