Efcore: Add-Migration EntityFramework Core 2.0 trying to select from table in an empty database

Created on 30 Aug 2017  路  7Comments  路  Source: dotnet/efcore

I'm trying to run the add-migration command for my database context and for some reason it's trying to do a select on a table that doesn't even exist yet (running on an empty database). The command I'm running is:

Add-Migration -context MyDbContext MyDb-1.0

I immediately get an error:

An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: Invalid object name 'AccountTypes'.

Looking at the stacktrace I see the command was trying to do a select statement on a non-existing (yet) table:

fail: Microsoft.EntityFrameworkCore.Database.Command[200102]
      Failed executing DbCommand (27ms) [Parameters=[@__value_0='?'], CommandType='Text', CommandTimeout='30']
      SELECT TOP(1) [p].[Id], [p].[AccountType]
      FROM [AccountTypes] AS [p]
      WHERE [p].[Id] = @__value_0

Not sure what is going on here. I'm using ASP.NET core 2.0 with EF core 2.0. I didn't have a problem doing this with core < 2.0.Any ideas?

closed-question

Most helpful comment

Was there application code in the callstack? You may need to move some code from Startup.Configure() or the DbContext constructor...

All 7 comments

Update: So I went ahead and manually created the AccountTypes table. Add-Migration works since it doesn't fail on the select statement. However running Update-Database fails because, like Add-Migration, it first does a select on my AccountTypes table and then tries to create the AccountTypes table... of course it's going to fail.

Why is Add-Migration / Update Database commands trying to select a table? Shouldn't it just be checking to make sure it can connect to the database and then just do the create tables?

Was there application code in the callstack? You may need to move some code from Startup.Configure() or the DbContext constructor...

The recommendation from the Hosting team is to perform app initialization inside of Program.Main().

@bricelam Thanks that was it. I had a service injected into Startup.Configure() that, when called, will seed some data into the DB. I commented out that line and Add-Migration / Update-Database commands work like a charm! Funny this all worked in 1.1 and 1.0.

I'm googling around and even in core 2.0 all bootstrap services, e.g. data seeding, are still in Startup.Configure(). I'm not sure how to inject or retrieve the data seeding service I have in Program.Main().

This Stack Overflow answer gives good guidance.

@bricelam Yup that SO answer did the trick! Got it working using an extension method for invoking my data seeding service. Thanks!

Thanks! It helped me much. I tried to initialize DbContext in it's constructor but it have to be done from out of DbContext class.

Was this page helpful?
0 / 5 - 0 ratings