【发布时间】:2021-07-27 03:23:21
【问题描述】:
我正在尝试在 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; }
}
查询.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 类型对象数据的列表。但在 Insomnia 客户端显示错误。我认为下面的代码有问题
descriptor.Field(g => g.GetList())
.Type<MyDataDataObjectType>().Name("GetList");
我在 POST 调用中发送以下内容
query{
a:GetList
{
Code
}
}
错误:
{ “错误”:[ { "message": "意外执行错误", “地点”:[ { “行”:4, “列”:4 } ], “小路”: [ “一种”, “代码” ], “扩展”:{ "message": "父级不能转换为 MyData。", "stackTrace": " 在 HotChocolate.Execution.Processing.MiddlewareContext.SourceT\r\n 在 HotChocolate.Execution.Processing.MiddlewareContext.ParentT\r\n 在 lambda_method65(Closure , IResolverContext)\r\n 在 HotChocolate.Types.FieldMiddlewareCompiler .c__DisplayClass3_0.
d.MoveNext()\r\n--- 从先前位置结束堆栈跟踪 ---\r\n 在 HotChocolate.Execution.Processing.ResolverTask.ExecuteResolverPipelineAsync(CancellationToken cancelToken)\r \n 在 HotChocolate.Execution.Processing.ResolverTask.TryExecuteAsync(CancellationToken cancelToken)" } } ], “数据”: { “一种”: { “代码”:空 } } }
提前感谢您的帮助。
【问题讨论】:
标签: graphql dapper asp.net-core-5.0 hotchocolate