Pomelo.EntityFrameworkCore.MySql: 此 MySqlConnection 已在使用中

Pomelo.EntityFrameworkCore.MySql: This MySqlConnection is already in use

目前我正在开发一个使用 Entity Framework 和 Hangfire 的 ASP.NET API。到目前为止,一切都很好。 当我尝试在 Hangfire 后台作业期间将更改保存到我的数据库(使用 Entity Framework 中的 Pomelo.MySQL 连接器)时,我得到标题中提到的异常。

我的一些代码:

Program.cs

...
if (app.Environment.IsDevelopment())
{
    Jobs.Enqueue();
}
...

Jobs.cs

public static class Jobs
{
        public static void Enqueue()
        {
            RecurringJob.AddOrUpdate<AppointmentList>(x => x.BackgroundJob(), Conversion.Cron(0));
        }
}

AppointmentList.cs

public class AppointmentList
{
        private readonly IMailService _mailService;
        private readonly INotificationService _notificationService;


        public AppointmentList(IMailService mailService,
            INotificationService notificationService)
        {
            _mailService = mailService;
            _notificationService = notificationService;
        }

        public void BackgroundJob()
        {
            var unhandledNotifications = _notificationService.GetUnhandledNotifications();

            foreach (var unhandledNotification in unhandledNotifications)
            {
                ...
                _mailService.SendAppointmentList(unhandledNotification);
            }
        }
}

MailService.cs

public class MailService : IMailService
{
        private readonly TattoogendaDbContext _context;
        private readonly IConfiguration _configuration;

        public MailService(TattoogendaDbContext context, IConfiguration configuration)
        {
            _context = context;
            _configuration = configuration;
        }
        
        ...

        public bool SendAppointmentList(NotificationLog notificationLog)
        {
            ...

            notificationLog.Destination = notificationLog.Project.Customer.Email;
            notificationLog.Title = notificationLog.Notification.Title;
            notificationLog.Body = body;
            notificationLog.HandledAt = DateTime.Now;
            notificationLog.Remarks = exception is null ? "": exception.Message;
            _context.SaveChanges(); // Exception is thrown here

            return result;
        }
}

这个是我自己想出来的。

在 NotificationService.cs 中,我不得不在 LINQ 的开头添加一个 .ToList()

...
public IEnumerable<NotificationLog> GetUnhandledNotifications()
    {
        return _context.NotificationLogs.Where(l => l.HandledAt == null)
            .Include(l => l.Notification)
            .Include(l => l.Project)
            .ThenInclude(p => p.ProjectAppointments)
            .ThenInclude(a => a.ProjectAppointmentType)
            .Include(l => l.Project)
            .ThenInclude(p => p.Customer)
            .Include(l => l.Project)
            .ThenInclude(p => p.Artist)
            .ThenInclude(a => a.User)
            .Include(l => l.Shop)
            .ThenInclude(s => s.NotificationSettings).ToList();
    }
...