EF6 MigrateDatabaseToLatestVersion initializer stuck after Update-database - asp.net

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.

Related

EF Core running migrations from asp.net code throws exception

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)

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

How do you apply pending explicit migrations in visual studios community edition? (ASP.Net)

I am trying to modify my code first migration so that I can add a new table to the db, called "GunControl." However, when I enter "Add-Migration GunControl" in the package manager, I get the error message:
"Unable to generate an explicit migration because the following explicit migrations are pending: [201705171404346_Questionnaire]. Apply the pending explicit migrations before attempting to generate a new explicit migration."
QuestionnaireDbEntities.mdf is the name of by db, and GunControl inherits from the class Questionnaire. I have looked everywhere online, and I can't find a way to do this. Thank you so much for your time!
This occurs because you have an existing database already that you're connecting to. The database keeps track of what migrations have been applied to it and when you run Add-Migration it compares the database schema with your models and sees that you've created a migration previously (201705171404346_Questionnaire) which has not yet been applied to the actual database. Because of this, the new migration can't determine what has changed in the schema when comparing the database.
Your options are:
Run Update-Database to apply the previous migration.
Delete the migration file 201705171404346_Questionnaire.cs and then run Add-Migration again which will contain both sets of changes.
Delete the entire database and all migration files, then run Add-Migration to create the initial schema.

.Net Core Contoso Tutorial During migrations and error is encountered with an object already in the database

While studying and following along with the migration section, I had done the initial, then followed it up with the next two migrations as shown. On the last migration an error of the "course" is already in the database. Exact error "There is already an object named 'Course' in the database." I removed all migrations and re-did the shown migrations, each time ending with the same error.
Why does this type of error occur? A
nd how to completely remove all migrations (my migration folder was blank) so that one can move forward with the next migration. Am I missing something?
This is potentially a big topic to fit into a single answer. I will try to give you an overview, background and advice. Further reading will be required to get a full understanding of how Entity Framework should be utilised. I will mostly cover Migrations, as that is the main thrust of your question.
OVERVIEW
Entity Framework Migrations offer the ability to rollback the changes made to a database, back to the schema of the database that is contained in a specified Migration; e.g. to undo schema changes by returning the database to a previous schema - and also to return it to its original state.
Note that data loss can occur when applying or rolling back Migrations, but in your scenario this is possibly not important.
The command to return a database to a specific Migration is:
Update-Database -TargetMigration:"migration_name"
The command to return to the initial, original state of the database is:
Update-Database –TargetMigration: $InitialDatabase
Entity Framework also has the optional concepts of Database Initialization and Initialization Strategies, that allow a developer to specify that the database should only be created once, or dropped and created each time an application is run, depending if their Code First model has changed. Please refer to these tutorials for more in depth coverage of Database Initialization.
As you say you have no Migration files in your Migrations folder, let us continue...
BACKGROUND
When you first run the Enable-Migrationscommand, it will create a class that is used for managing subsequent application of Migrations.
When you generate your first Migration, by executing, for example:
Add-Migration InitialCreate
This will create an InitialCreate file within your Migrations folder, that contains the initial schema, according to your class model that will be persisted by Entity Framework. The example name InitialCreate is optional and can be anything you wish - it is simply a label that can be referred to later.
Subsequently, when you issue an Add-Migration command, further Migrations are created to apply schema changes related to your classes; they will be added to your Migrations folder, but, not yet applied to the database.
The Migrations can then be applied to your database by issuing the Update-Database command. If executed without parameters, the database schema is updated to the schema defined by the latest Migration.
If you are following the Contoso tutorial correctly, you should have several Migrations, one of which contains the word 'Initial' in its name, as part of the convention.
ADVICE
If you do not see these, it is likely that you have not initialised Migrations, by issuing the command Enable-Migrations.
After executing Update-Database for the first time, verify this also creates a database table named __MigrationHistory - this tracks the schema versions and Migrations that have been applied.
You have possibly applied Migrations in an incorrect order, and it now does not match your class structure, or, is out of sync with the schema tracking within the database.
In your current circumstances, as you are following a tutorial, it is probably best to delete your database, and recreate it following the steps outlined by Microsoft, paying special attention to the output from Enable-Migrations, Add-Migration and Update-Database commands, verifying the database schema at each step.
REFERENCE
For reference, the overview of how Migrations should be utilised, can be found on MSDN here.
A walkthrough of using Migrations with MVC can be found here

Error while updating database code first EF

I have a .net MVC project which works with Code first approach, I need to add a new table and the migration folder already exists and contains a lot of migrations files that have been made before; when I run Add-Migration:
Unable to generate an explicit migration because the following
explicit migrations are pending:
[201304230714010_InformationalMessage, 201305231312259_Remove
hardcoded currencies ]. Apply the pending explicit migrations before
attempting to generate a new explicit migration.
So I run Update-Database –Verbose it gives me error:
There is already an object named 'InformationalMessage' in the
database.
which seems that it goes to execute the migrations files again and it is normal to give me that error as it already exist.
Can anyone help me to how to update this code with my new table?
Error says you are already having pending migration so first run the pending migration and then run your migration.
update-database -verbose (run first pending migration).
Add-migration <nameOfMigration> (add your migration).
Update-database -verbose (run your migration in the last).
I've run into that occasionally. What I do is comment out the CreateTable command for that migration in the Up() and Down() methods. When I need a production script I am usually rolling my changes up into a single update anyways.
Temporarily add DropTable("InformationalMessage") to your copy of the 201304230714010_InformationalMessage migration – be warned, this will lose any data currently in that table, but should get you to a point where you can add your new migration … if this is a concern, make a backup of the actual table data while working on your migration.
You either need to run "update-database" from the package manager console to push your changes to the database OR you can delete the pending migration file ([201304230714010_left]) from your Migrations folder and then re-run "add-migration" to create a brand new migration based off of your edits.

Resources