Search code examples
.net-coreentity-framework-coreeager-loadingbackground-serviceasp.net-core-hosted-services

Eager loading doesn't work with BackgroundService


I'm trying to load related entities in a console application that runs a BackgroundService, but it doesn't load related entities, I have had this problem for hours now and I just noticed it happens only in the BackgroundService, tried the same DbContext in a web application by injecting the DbContext class in the Index page model, without a problem.

Here's the code from the console application:

the Background Service:

public class MyService : BackgroundService
{
    private readonly MyDbContext _context;

    public MyService(MyDbContext context)
    {
        _context = context;
    }

   protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    { 
                     //Jobs always empty!
        var theBatch = _context.Batches.Include(x => x.Jobs).FirstOrDefault();
     } 
}

the program file:

class Program
{
    static async Task Main(string[] args)
    {
        using IHost host = CreateHostBuilder(args).Build();
        await host.RunAsync();
    }

    static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args)
       .ConfigureServices((context, services) =>
       {
           services.AddLogging()
         .AddDbContext<MyDbContext>(options => options
         .UseSqlServer(context.Configuration.GetConnectionString("MyConnection")))

         .AddHostedService<MyService>()
         .BuildServiceProvider();
       });
}

I'm using .NET 5 and EF Core 5.0.12


Solution

  • OK, I'm writing this while I'm really angry for the hours and the effort spent on this problem, I don't know who to blame, Microsoft or the person who installed EF 6 in .NET core project. Microsoft made it difficult to find out the source of the problem.

    I was using Include from System.Data.Entity namespace not Microsoft.EntityFrameworkCore

    I figured it out by a mere coincidence, I used FirstOrDefaultAsync without a specific reason, and got this weird exception:

    'The provider for the source IQueryable doesn't implement IDbAsyncQueryProvider. Only providers that implement IDbAsyncQueryProvider can be used for Entity Framework asynchronous operations.

    When I looked at it, I found that I was using the wrong namespace for FirstOrDefaultAsync (System.Data.Entity instead of Microsoft.EntityFrameworkCore) when I changed the namespace, everything worked!