ASP .NET Core 3.0 App with Entity Framework Core freezes while seeding DB with no exception thrown

asp.net-core deadlock entity-framework-core

Question

Since yesterday I am running into a weird problem with my DB seeding method and I cannot seem to figure it out.

I created a class to seed my DB, registered it for DI and call its seeding method from Startup.Configure. Inside I ensure the DB is created, then I generate data to fill it with. Adding the first few sets of data works just fine. However at some point I need to add a slightly larger quantity of data to a table (200 rows).

I created a List to store the entries and proceed to add them by calling await _context.AddRange(List) followed by await _context.SaveChangesAsync(). The execution freezes while saving. Other Tasks, like a background task that I register are still running. There is also no Exception thrown. If I change both executions to their synchronous counterparts it will work. This leads me to think that I have a deadlock. But since the background service is still running and I cannot debug what's going on in my seeding method I have no idea if this even could be a deadlock or not.

I could just go ahead and use the synchronous calls but I feel like I am missing something here and am likely to run into the problem again. The weirdest part is that the data that I am trying to add to the table only starting freezing the execution after I added more columns. Previously I called await _context.Add(data) on all of the rows and only called await _context.SaveChangesAsync() at the end. At that point the table had about 15 columns. When I extended the table to have 30 columns, these and the aforementioned calls do not work anymore. The only lead for me could be the increased amount of data that has to be added which makes running into a deadlock more likely but otherwise I am out of ideas.

1
0
4/9/2020 10:01:00 AM

Accepted Answer

I created a class to seed my DB, registered it for DI and call its seeding method from Startup.Configure.

You shouldn't be running anything in Startup.Configure, let alone something async. If you need to run something at app startup, do it in your Program.Main, and since this is async, you'll need to switch to using an async Main:

public static async Task Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();

    var seed = host.Services.GetRequiredService<SeedClass>();
    await seed.SeedAsync();

    await host.RunAsync();
}

That said, this is not the way you're supposed to be seeding with EF, regardless. Since EF 2.1, you seed via HasData in OnModelCreating:

modelBuilder.Entity<Blog>().HasData(new Blog {BlogId = 1, Url = "http://sample.com"});

See the docs for more detail.

0
4/9/2020 2:19:11 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow