已经在执行命令

问题描述 投票:0回答:1

我正在尝试为我正在开发的Web应用程序运行后台工作者。我正在使用Npgsql作为EF Core提供程序。

为澄清起见,我为DbContext注入了瞬态生命周期,并允许在连接字符串中进行池化,但是,每当我尝试对其进行测试时,都会出现以下错误:

Npgsql.NpgsqlOperationInProgressException:命令已经在执行中:[我在这里查询]

我这样设置了Program类:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                // Get the configuration
                IConfiguration config = hostContext.Configuration;

                // DbContext
                services.AddDbContext<MyDbContext>(options => options.UseNpgsql(config.GetConnectionString("PostgreSQLString")), ServiceLifetime.Transient);

                services.AddHostedService<Worker>();
                services.AddScoped<IDTOService, BackgroundDTOService>();
            });
}

然后引导到我的Worker

public class Worker : BackgroundService
{
    private Logger logger;

    public Worker(IServiceProvider services, IConfiguration configuration)
    {
        this.Services = services;

        var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
        optionsBuilder.UseNpgsql(configuration.GetConnectionString("PostgreSQLString"));
        var context = new StatPeekContext(optionsBuilder.Options);

        this.logger = new Logger(new LogWriter(context));
    }

    public IServiceProvider Services { get; }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        this.logger.LogInformation("ExecuteAsync in Worker Service is running.");
        await this.DoWork(stoppingToken);
    }

    private async Task DoWork(CancellationToken stoppingToken)
    {
        using (var scope = Services.CreateScope())
        {
            var context = scope.ServiceProvider.GetRequiredService<MyDbContext>();
            var dtoService = scope.ServiceProvider.GetRequiredService<IDTOService>();
            await dtoService.ProcessJSON(stoppingToken);
        }
    }

    public override async Task StopAsync(CancellationToken cancellationToken)
    {
        this.logger.LogInformation("Worker service is stopping.");
        await Task.CompletedTask;
    }
}

导致我的BackGroundDTOService

public class BackgroundDTOService : IDTOService
{
    private int executionCount = 0;
    private Logger logger;
    private MyDbContext context;
    private DbContextOptionsBuilder<MyDbContext> optionsBuilder;

    public BackgroundDTOService(IConfiguration configuration, MyDbContext context)
    {
        this.optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
        this.optionsBuilder.UseNpgsql(configuration.GetConnectionString("PostgreSQLString"));

        this.logger = new Logger(new LogWriter(new MyDbContext(this.optionsBuilder.Options)));

        this.context = context;
    }

    public async Task ProcessJSON(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            this.executionCount++;

            this.logger.LogInformation($"DTO Service is working. Count: {this.executionCount}");

            this.ProcessTeams();

            await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
        }
    }

    public void ProcessTeams()
    {
        // Add Any Franchises that don't exist
        var franchiseDumps = this.context.RequestDumps.Where(rd => rd.Processed == false && rd.DumpType == "leagueteams");
        foreach (RequestDump teamDump in franchiseDumps)
        {
            var league = this.context.Leagues.Include(l => l.Franchises).FirstOrDefault(l => l.Id == teamDump.LeagueID);
            var teams = Jeeves.GetJSONFromKey<List<DTOTeam>>(teamDump.JsonDump, "leagueTeamInfoList");

            foreach (DTOTeam team in teams)
            {
                this.UpdateFranchise(team, league);
            }

            this.logger.LogInformation($"DTO Service Processed League Teams on count {this.executionCount}");
        }

        this.context.SaveChanges();
    }

[尝试获取franchiseDumps时,似乎在紧紧抓住league之后立即发生错误

c# entity-framework-core npgsql
1个回答
0
投票

您能否尝试实现查询:

 var franchiseDumps = this.context.RequestDumps.Where(rd => rd.Processed == false && rd.DumpType == "leagueteams").ToList();
© www.soinside.com 2019 - 2024. All rights reserved.