Currently I'm working on an ASP.NET API which uses Entity Framework and Hangfire. So far so good. When I try to save changes to my database (using the Pomelo.MySQL connector in Entity Framework) during a Hangfire background job I get the exception mentioned in the title.
Some of my code:
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;
}
}
Figured this one out myself.
In NotificationService.cs I had to add a
.ToList()
at the of the LINQ.