I'm tried to Add-Migration in my asp.net core application but migration not working
Please any one give me ans for this what's the issue
Please check this image i added all information reading issue everything i combined into single screen-shot for more clarification
you need to provide a name for the migration just like this Add-Migration V1, after creating the migration you need to run the Update-Database to apply the migration. BTW if there is any build error nothing will work. you need to ensure there is not build error.
I would do this:
1) Remove the Migrations folder in your project
2) Delete the _MigrationHistory table from your database.
3) Run the Enable-Migrations command from your Package Manager Console.
4) Run the Add-Migration Init command to create a migration.
5) Remove all of the code lines in Up() function for the initial migration. (To create an empty migration.)
6) Run the Update-Database command to apply your empty migration.
7) Make changes to your code first model for preparing to adding your real migration.
8) Run the Add-Migration InitNew command to create a new migration.
9)Run the Update-Database command to apply the changes.
Taken from: https://stackoverflow.com/a/44019743/6221069
Related
I am trying to use Migrations in my project but when trying to update the database, only the base migration is applied.
I have a total of two migrations.
The Base migration(initialy created)
CreateNewProperty(Change includes adding a new property to one of the tables)
I see Enable-Migration mentioned in the Microsoft Documentation but it seems to have gone obsolete.
In addition to this, I also a mention of using the following in the Context class to enable latest migrations, but SetInitialier() method is no longer available:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DatabaseContext, EF6Console.Migrations.Configuration>());
When I try to remove all migrations and bring it to the initial state by executing:
update-databse 0
it fails with the following error:
ALTER TABLE DROP COLUMN failed because column 'test' does not exist in
table 'Item'.
which is basically the update done in the CreateNewproperty migration and this error is expected as this migration was never applied. Why is EF trying to downgrade a migration, when it did not apply it in the first place.
Use below command to Migrate to a Specific Version (Including Downgrade)
update-database -targetmigration:MigrationName
More information visit
https://learn.microsoft.com/en-us/ef/ef6/modeling/code-first/migrations/#migrate-to-a-specific-version-including-downgrade
Is it possible that your snapshot has become messed up somehow? You could try deleting that and then create a new migration (one that you could throw away) to rebuild it. Then try running update-database again.
In order to get rid of writing Migration and Update commands each time your data model changes, you can simply write two command line files as EF CLI and just click them to execute Migration and Update commands. These command files create the Migration name using the date and time of your machine.
For the add migration file set a name such as 01-add_migration.cmd (with .cmd extension) with the following content:
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c_%%a_%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME: =0%") do (set mytime=%%a%%b)
dotnet ef --startup-project ../Product.Api migrations add V%mydate%_%mytime% -o Persistence/Migrations -c ApplicationDbContext
pause
and for the update database set e file name such as 02-update_db.cmd with the content as bellow:
dotnet ef --startup-project ../Product.Api database update -c ApplicationDbContext
pause
You can add other parameters of Migration and Update commands as well.
So in my opinion, if you have created lots of migrations and started changing up the classes during the creation of your app, you might have missed something, which happens to many developers.
If that is your case, you should try to delete the migrations history in the database and the tables that were created using the migrations.
The migrations history table is located in the tables folder of the database and looks like this:
Then delete the migrations folder that you have in your Project.
Search for it in the solution explorer.
It should look something like this:
Next, do what you would do from the beginning.
Add-Migration [Name]
Update-Database
Okay, so this is what worked:
I deleted the database completely and then ran the update-databse command.
On running this, first the base migration was applied and then the second migration. And now when I create a third migration and apply it is working as expected!
Every time I want to update database with code-first migrations I need to open Package Manager Console, set up Default project to project where I have migrations and write command:
update-database -startupprojectname CoreConsole
How I can set up in my solution:
1) Default project in dropdown where migrations are stored
2) startupprojectname where config with connection settings is stored
The target is to only write command update-database in console without any parameters and additional dropdown selections.
ASP.NET WebAPI app published on Azure, Entity Framework code first.
After publishing with migrations executing on application start (first pic) I can't add new migration and work with database context ("model backing the 'DatabaseContext' context has changed since the database was created" exception). On adding new migration EF breaks with error:
Unable to generate an explicit migration because the following explicit migrations are pending: [migration name]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
Looks like EF doens't see migrations from __MigrationHistory table. I checked this table and last migrations exists.
In web.config there are only one connection string.
If it's important, DatabaseContextWithoutCache inherit DatabaseContext (they have different DbConfigurationType).
After adding null initializer Database.SetInitializer<DatabaseContext>(null); to database context it works but I still can't add any migration.
Why does Entity Framework doesn't see that migration is already appended to database? update-database breaks because there are already tables and columns in db.
EDIT:
In my migration list 2 migrations. I rolled back to init (first) migration and remove second. Then add-migration (now it contains changes from second and new changes) and run update-database. It works.
But EF ignore that db is up-to-date and breaks with "model backing the 'DatabaseContext' context has changed since the database was created" exception.
OMG I DON'T UNDERSTAND
I had this issue recently under VS 2013. If in the Package Manager Console you run the command add-migration {name} (optionally adding -startupprojectname {MyProjectName}) the EF should generate a new migration file for you. If that migration file has any content, then it believes you are not where you should be and you should then run update-database with that new migration in place.
Unfortunately it does seem possible to get caught in a loop with this (it happened to me) and there are quite a few SO Q&As which concern this. Very best of luck solving it.
As the error suggests, there is a migration pending against the database.
Use the following command from the package manager (replace values with your own)
update-database -projectname yourprojectname -connectionstring "yourconnectionstring"
Then, create your new migration....
add-migration yournewmigrationname -projectname yourprojectname -connectionstring "yourconnectionstring"
And finally, run the newly created migration
update-database -projectname yourprojectname -connectionstring "yourconnectionstring"
Ok, so I've read the other threads and I'm still not getting anywhere. I have my project set as Startup, I have a connection string in the App.config. I'm using LocalDb in VS2013.
If I delete my database, it creates it ok, BUT, if I try
PM> Enable-Migrations
it tells me that Migrations have already been enabled in project TestCodeFirst. If I then try
PM> Update-Database
it tells me No migrations configuration type was found in the assembly 'TestCodeFirst', and suggests that I try to Enable-Migrations. I have tried adding the -Force parameter. The Migrations folder has only Configuration.cs, and in that file, I've tried setting AutomaticMigrationsEnabled both true and false, with no difference. I'm not lost, cause I can always delete my DB and rerun, but I don't see any way to make the migrations feature work as advertised. Confession: At one point, I took PM's suggestion and tried deleting the Migrations folder. That may have been a mistake.
I have this code snippet in my Program.cs file (I'm just testing this in a console app):
class Program
{
static void Main(string[] args)
{
using (TestContext db = new TestContext())
{
...
Db.ThisOrThat.Add(stuff);
Db.SaveChanges();
...
}
}
}
The Entity Framework Code First approach creates your database automatically, a table will be automatically added to the database by the Code First that is helpful to record the schema of database synchronization with the related model class. Entity Framework throws an error, the database is not synchronized with the class.
To perform the Code First Migration in the database:
Delete the MDF file of the database
Open Package Manager Console and write the following command
Enable-Migrations -ContextTypeName ConsoleApp.Models.TestContext
It creates the Configurations.csclass, then you can edit your code
After Building the application enter the following command in the Package Manager Console:
add-migration Initial
update-database
Note: If you receive an error then you need to ensure that the mdf file is deleted permanently from the App_Data folder. Otherwise you can go to the SQL Server Object Explorer, expand the localDb server and in the Database option ensure that the mdf file is deleted.
Debug the appliction
You'll need to run the "Add-Migration" command that will actually add the migration that the 'Update-Database' command will run:
Code First Migrations
"Add-Migration will scaffold the next migration based on changes you have made to your model since the last migration was created"
I'm using EF 6.0 for my project in C# with manual migrations and updates. I have about 5 migrations on the database, but I realised that the last migration was bad and I don't want it. I know that I can rollback to a previous migration, but when I add a new (fixed) migration and run Update-Database, even the bad migration is applied.
I was trying to rollback to the previous migration and delete the file with bad migration. But then, when I try to add new migration, I get error when updating database, because the migration file is corrupted (more specifically, first line of code rename the table A to B and is next lines, EF is trying to update table with name A - maybe it is some EF bug).
Is there some query I can run, which would tell EF something like "Forget last migration like it never existed, it was bad"? Something like Remove-Migration.
Edit1
I found solution suited for me. Changing model to the good state and run Add-Migration TheBadMigration -Force. This will re-scaffold the last, not applied migration.
Anyway, this still not answer the original question completely. If I UpdateDatabase to the bad migration, I did not found good way how to rollback and create new migration, excluding the bad one.
Thanks
You have 2 options:
You can take the Down from the bad migration and put it in a new migration (you will also need to make the subsequent changes to the model). This is effectively rolling up to a better version.
I use this option on things that have gone to multiple environments.
The other option is to actually run Update-Database –TargetMigration: TheLastGoodMigration against your deployed database and then delete the migration from your solution. This is kinda the hulk smash alternative and requires this to be performed against any database deployed with the bad version.
Note: to rescaffold the migration you can use Add-Migration [existingname] -Force. This will however overwrite your existing migration, so be sure to do this only if you have removed the existing migration from the database. This does the same thing as deleting the existing migration file and running add-migration
I use this option while developing.
As the question indicates this applies to a migration in a development type environment that has not yet been released.
This issue can be solved in these steps:
Restore your database to the last good migration.
Delete the bad migration from your Entity Framework project.
Generate a new migration and apply it to the database.
Note: Entity Framework and Entity Framework Core use slightly different command names
Step 1: Restore to a previous migration
If you haven't yet applied your migration you can skip this part. To restore your database schema to a previous point issue the Update-Database command with -TargetMigration option to specify the last good migration. For EFCore use Update-Database "Name-of-Migration"
If your entity framework code resides in a different project in your solution, you may need to use the '-Project' option or switch the default project in the package manager console.
Update-Database –TargetMigration: <name of last good migration>
For EFCore:
Update-Database <name of last good migration>
To get the name of the last good migration use the 'Get-Migrations' command to retrieve a list of the migration names that have been applied to your database, use 'Get-Migration' without the 's' if you are using EFCore.
PM> Get-Migrations
Retrieving migrations that have been applied to the target database.
201508242303096_Bad_Migration
201508211842590_The_Migration_applied_before_it
201508211440252_And_another
This list shows the most recent applied migrations first. Pick the migration that occurs in the list after the one you want to downgrade to, ie the one applied before the one you want to downgrade. Now issue an Update-Database.
Update-Database –TargetMigration: "<the migration applied before it>"
For EFCore:
Update-Database "<the migration applied before it>"
All migrations applied after the one specified will be down-graded in order starting with the latest migration applied first.
EF will reject the command if your downgrade might cause data loss. Use the '-Force' option to accept the data loss and allow the command to execute.
Step 2: Delete your migration from the project
If you are using Entity Framework Core you can use the 'remove-migration' command, for Entity Framework, delete the files of the unwanted migration in your EF project 'Migrations' folder manually. At this point, you are free to create a new migration and apply it to the database.
For EFCore:
remove-migration name_of_bad_migration
Step 3: Add your new migration
add-migration my_new_migration
Step 4: Apply your migration to the database
update-database
For those using EF Core with ASP.NET Core v1.0.0 I had a similar problem and used the following commands to correct it (#DavidSopko's post pointed me in the right direction, but the details are slightly different for EF Core):
Update-Database <Name of last good migration>
Remove-Migration
For example, in my current development the command became
PM> Update-Database CreateInitialDatabase
Done.
PM> Remove-Migration
Done.
PM>
The Remove-Migration will remove the last migration you applied. If you have a more complex scenario with multiple migrations to remove (I only had 2, the initial and the bad one), I suggest you test the steps in a dummy project.
There doesn't currently appear to be a Get-Migrations command in EF Core (v1.0.0) so you must look in your migrations folder and be familiar with what you have done. However, there is a nice help command:
PM> get-help entityframework
Refreshing dastabase in VS2015 SQL Server Object Explorer, all of my data was preserved and the migration that I wanted to revert was gone :)
Initially I tried Remove-Migration by itself and found the error command confusing:
System.InvalidOperationException: The migration '...' has already been
applied to the database. Unapply it and try again. If the migration
has been applied to other databases, consider reverting its changes
using a new migration.
There are already suggestions on improving this wording, but I'd like the error to say something like this:
Run Update-Database (last good migration name) to revert the database schema back to to that state. This command will
unapply all migrations that occurred after the migration specified to
Update-Database. You may then run Remove-Migration (migration name to remove)
Output from the EF Core help command follows:
PM> get-help entityframework
_/\__
---==/ \\
___ ___ |. \|\
| __|| __| | ) \\\
| _| | _| \_/ | //|\\
|___||_| / \\\/\\
TOPIC
about_EntityFrameworkCore
SHORT DESCRIPTION
Provides information about Entity Framework Core commands.
LONG DESCRIPTION
This topic describes the Entity Framework Core commands. See https://docs.efproject.net for information on Entity Framework Core.
The following Entity Framework cmdlets are included.
Cmdlet Description
-------------------------- ---------------------------------------------------
Add-Migration Adds a new migration.
Remove-Migration Removes the last migration.
Scaffold-DbContext Scaffolds a DbContext and entity type classes for a specified database.
Script-Migration Generates a SQL script from migrations.
Update-Database Updates the database to a specified migration.
Use-DbContext Sets the default DbContext to use.
SEE ALSO
Add-Migration
Remove-Migration
Scaffold-DbContext
Script-Migration
Update-Database
Use-DbContext
You can also use
Remove-Migration -Force
This will revert and remove the last applied migration
I am using EF Core with ASP.NET Core V2.2.6. #Richard Logwood's answer was great and it solved my problem, but I needed a different syntax.
So, For those using EF Core with ASP.NET Core V2.2.6 +...
instead of
Update-Database <Name of last good migration>
I had to use:
dotnet ef database update <Name of last good migration>
And instead of
Remove-Migration
I had to use:
dotnet ef migrations remove
For --help i had to use :
dotnet ef migrations --help
Usage: dotnet ef migrations [options] [command]
Options:
-h|--help Show help information
-v|--verbose Show verbose output.
--no-color Don't colorize output.
--prefix-output Prefix output with level.
Commands:
add Adds a new migration.
list Lists available migrations.
remove Removes the last migration.
script Generates a SQL script from migrations.
Use "migrations [command] --help" for more information about a command.
This let me role back to the stage where my DB worked as expected, and start from beginning.
First, Update your last perfect migration via this command :
Update-Database –TargetMigration
Example:
Update-Database -20180906131107_xxxx_xxxx
And, then delete your unused migration manually.
As of .NET Core 2.2, TargetMigration seems to be gone:
get-help Update-Database
NAME
Update-Database
SYNOPSIS
Updates the database to a specified migration.
SYNTAX
Update-Database [[-Migration] <String>] [-Context <String>] [-Project <String>] [-StartupProject <String>] [<CommonParameters>]
DESCRIPTION
Updates the database to a specified migration.
RELATED LINKS
Script-Migration
about_EntityFrameworkCore
REMARKS
To see the examples, type: "get-help Update-Database -examples".
For more information, type: "get-help Update-Database -detailed".
For technical information, type: "get-help Update-Database -full".
For online help, type: "get-help Update-Database -online"
So this works for me now:
Update-Database -Migration 20180906131107_xxxx_xxxx
As well as (no -Migration switch):
Update-Database 20180906131107_xxxx_xxxx
On an added note, you can no longer cleanly delete migration folders without putting your Model Snapshot out of sync. So if you learn this the hard way and wind up with an empty migration where you know there should be changes, you can run (no switches needed for the last migration):
Remove-migration
It will clean up the mess and put you back where you need to be, even though the last migration folder was deleted manually.
For EF 6 here's a one-liner if you're re-scaffolding a lot in development. Just update the vars and then keep using the up arrow in package manager console to rinse and repeat.
$lastGoodTarget = "OldTargetName"; $newTarget = "NewTargetName"; Update-Database -TargetMigration "$lastGoodTarget" -Verbose; Add-Migration "$newTarget" -Verbose -Force
Why is this necessary you ask? Not sure which versions of EF6 this applies but if your new migration target has already been applied then using '-Force' to re-scaffold in Add-Migration will not actually re-scaffold, but instead make a new file (this is a good thing though because you wouldn't want to lose your 'Down'). The above snippet does the 'Down' first if necessary then -Force works properly to re-scaffold.
Be sure you don´t have error in project files, even in your migration files, I had an error in my last migration file and did not allow me remove it.