EF Core running migrations from asp.net code throws exception - asp.net

I am using EF core for the first time in my asp.net WebApi application (REST services),m using the SQLite provider. I have installed the Nuget package v2.0.1.
I have added my context , models etc, and everything seems to be working. I now wanted to try using Migrations. Following the documentation I have added my Migration, and all the expected files seem to have been created.
To test, I delete my SQLite database file and run the application,
however, when I call the `Migrate method in code, I get the following exception...
The weird thing is, when I close the debugger, the file and table is actually created. The migration table is present, but has no rows.
If I start again, ie delete the database, and then just run the migration from the Package Manager Console, then all works fine, ie I see...
PM> Update-Database
Applying migration '20180301030031_InitialCreate'.
Done.
PM>
an also the database is create, and this time the Migration table has the row of data I expect..
Any one have any ideas why this doesn't work when I just run it in code?
Thanks in advance for any help
[EDIT 1]
I get the same problem if I add a new Migration after just added a field. The first time I run, I gt the exception. If I then run again, it works!

I was considering just deleting this post, as the issue seemed to magically resolved itself.
I ran the same code (on the same database file) in a sample WPF application, and had no problems, so it seemed to be when running in the IIS process (and after doing iiresets to force the application to rerun the initialisation code which would then do the call to context.Database.Migrate();
At any rate, it now seems to work (but have no idea why it started working)

Related

after migrate sql runs after reboot of the application with no migration performed

I'm using Flyway 6.5.7 and I have a afterMigrate.sql that truncates a table. I thought the script would run only if a migration occurred AND if the migration is successful. But it always runs (for example after restart of the application)
Schema "A_SCHEMA" is up to date. No migration necessary.
Parsing afterMigrate.sql ...
Executing SQL callback: afterMigrate -
Is it correct? If so, is there a way to achieve the described behavior?
Note: org.flywaydb.core.Flyway#migrate returns 0 after restart of the application with no migration
Thanks
The way it works is the afterMigrate callback runs after any migration that didn't have an error. A successful migration is defined that way. So, in your situation, you called the migrate command. It ran successfully. It didn't migrate anything. However, it ran without an error, so the afterMigrate callback ran.
There is also the afterEachMigrate event which you can attach a callback to. This runs after each successful execution of a migration script; it doesn't run if migrate finds nothing to do, but on the downside it will run more than once if migrate finds multiple scripts that it needs to run. Depending on how often you push out new scripts, this might be a better solution for you.

New to ASP.NET Core 2.0 - Unable to configure app to use existing DB

I'm totally new to ASP.NET Core 2.0; I created a new Project with In-App Authentication.
When I run the application and try the Register function, I get an error message saying that
the table "AspNetUsers" does not exist.
That is OK and expected, I did not run the Migration scripts. For less confusion, I then deleted the Migration folder.
The problem I want to solve is I want the Register functions to register the user to my custom database. I already updated the settings in appsettings.json for this.
I made a Notepad++ search in the entire folder for AspNetUsers and found 0 hits. Yet, when I run the application again, the error message is the same, that the table "AspNetUsers" does not exist.
I am very confused. How does it know to look for that table if that text does not exist in the entire project directory?
How do I make it use my own database? I looked around, but I was unable to find any solutions. This is my last resort.
Thanks!
AspNetUser is table name for ApplicationUser object in database and there is no automatic migration in EF Core yet, so you have to generate migration files by your self. in database run following command nuget console:
Add-Migration Initial
after running this command a Migrations folder would be added. then run next command to apply migration to your database:
update-database

Schema not updating when publish web app from Visual Studio

I am building an ASP.NET MVC EF app with code-first migrations and hosting it in Azure with Azure SQL DB. The first time I published this, it went fine. But since then my models changed, and my schema in the Azure DB is not getting updated to match. When I deploy, I do have "Execute Code First Migrations" checked. When that wouldn't work, I deleted my DB and then recreated it in the Azure portal, figuring that would trigger it getting updated. But then that didn't work, so I set AutomaticMigrationsEnabled = True in the migration Configuration. It is STILL not working, so currently my DB in Azure has none of my tables. HOW can I get the DB in Azure to be forced to update to match my models so the published site will work?? I did try looking for if there's a way to script the VS local DB to a Create query and execute that in SQL management studio, but couldn't find how to do that.
If you have made sure that you have selected update database in the publish setting, and the connection string is correctc and its still not updating. Maybe the following will help for you:
I sometimes get an issue like this, it is quite frustrating, My publish file is correct and my settings are set to allow SQL updates to occur during publishing. But sometimes the database hasn't been updated and I get a nice "backing context has changed" error, sometimes the culprit is the migration table that hasn't been updated. Unfortunately the only sure way to get your databases in sync is to check what migration history they are both at, by comparing [dbo].[__MigrationHistory]
If your published server is missing the latest migration history, then you can generate an SQL script of that by typing into the package manager console:
Update-Database -Script -TargetMigration [migration name]
'migration name' should be the name of the last migration that your published server had, visual studio will generate sql script that can be used to bring the database up to the latest migration from that target migration.
Sometimes (though very rarely, its only happened once or twice for me) the above doesn't work for whatever reason (usually because migration files have been deleted), if that is the case then its a good idea to script the whole database, and cherry pick the sql you need from that.
Update-Database -Script -SourceMigration:0
This will generate a script for every migration, you can then cherry pick based on the changes you've made. The 'latest' changes will be closer to the bottom of the file. every migrational change will start with an if check:
IF #CurrentMigration < '201710160826338_mymigration'
BEGIN
You can use this to pick the bits that you need, if you do pick the SQL be sure to include the update to the migration history. It will be at the end of the if block and look something like this:
INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])
VALUES (N'201710101645265_test', N'API.Core.Configuration', 'Some long checksum')
Including the migration history will ensure that visual studio doesn't have the problem again.
Hope this helps.

EF code first won't recognize my DB

The problem I'm facing is the following:
I've been happily developing using code first with Entity Framework 6 and my SQLServer 2014 DB, updating the database, extracting scripts and so far everything worked perfectly. The problem is that suddenly it lost the track of my database and whenever I try to add a new migration it says I have to update the database because it still has pending migrations to apply.
If I look at the database I'm working with it shows everything is there, even the __MigrationHistory table with every migration I'd done registered. Even though I accept code first recommendation and try to update the database. And no surprises here... The first table it tries to create throws an error because it already exists.
Could you please provide me some guidance on this?
Thanks in advance,
P.
I just figured it what was all about.
It happens that I changed the project name and the entire namespaces. The namespace of the migration itself is stored on DB so when I changed the namespace the Code First was unable to find it on the migration table.
Updating the ContextKey for every migration to the current namespace solved my issue.
Thank you for your time.

EF6 MigrateDatabaseToLatestVersion initializer stuck after Update-database

I've created a project using EF code first but am stuck with the application unable to initialize (unless I enable automatic migrations which I don't want). This isn't a production system, but I'm trying to learn how to use code-first (and am struggling).
I've previously been through the steps to enable code first migrations, I have a configuration class with a seed method, and my project has worked previously.
I started getting an error:
"Unable to update database to match the current model because there
are pending changes and automatic migration is disabled"
So I've done the following:
Dropped the database completely, and created an empty one.
Deleted all existing DbMigration classes in the project
Created a new DbMigration class called 'InitialState' with the 'add-migration' command.
Run the 'update-database' command
The database update runs successfully, the seed method runs successfully and I can see the tables and data in my database. There is one row in the migration history table for my one migration 'InitialState'. It all looks fine, but when I run up the application, still get the same initial error. If I run the 'add-migration' and 'update-database' commands again, it creates a blank migration and updates, but I still get the error.
If I enable automatic migrations, an auto-migration entry appears in the migrations table and my app runs. But I don't want automatic migrations.

Resources