gpt4 book ai didi

c# - GraphQL 并行异步查询 c# EF Core 3.0

转载 作者:行者123 更新时间:2023-12-05 08:06:42 26 4
gpt4 key购买 nike

我正在尝试使用 2 个(或更多)异步子查询执行查询。遗憾的是,这是不可能的,因为 DbContext 一次只能处理 1 个请求。

项目正在使用:

  • Entity Framework 3
  • Graphql 3.0.0

错误

A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext.

类型:

Field<ListGraphType<A>>()
.Name("A")
.Description("query of A")
.ResolveAsync(async context =>
await repro.GetAllAAsync(context)
);

Field<ListGraphType<A>>()
.Name("B")
.Description("query of B")
.ResolveAsync(async context =>
await repro.GetAllBAsync(context)
);

查询:

query {
A {
id
}
B {
id
}
}

DbContextPool 没有解决问题,我不想使用 StructureMap。

有没有优雅的使用方式

  • 每个子查询有多个 dbContext
  • 等到 dbContext 空闲

最佳答案

我最近创建了一个解决 EF 并行执行问题的项目。你可以在这里看到实现

https://github.com/fenomeno83/graphql-dotnet-globalization-demo

特别是,这里有一个查询示例,您可以找到:

public class TestGroupQueries : ObjectGraphType
{
public TestGroupQueries(IHttpContextAccessor _httpContextAccessor)
{
Name = "testQueries";

FieldAsync<TestResponseType>(
"demoQuery",
arguments: new QueryArguments(new QueryArgument<NonNullGraphType<IntGraphType>> { Name = "input" }),
resolve: async context =>
{
//extension method that creates scope (IServiceScope) from IServiceProvider
using (var scope = _httpContextAccessor.CreateScope())
{

//call DemoQuery method of TestService; GetService is an extension method that use GetRequiredService from scope serviceprovider
return await scope.GetService<ITestService>().DemoQuery(context.GetArgument<int>("input"));
}
});


}

您在解析器中创建一个新范围并使用该范围的服务

关于c# - GraphQL 并行异步查询 c# EF Core 3.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59334502/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com