ef database updata is unable to find migration - entity-framework-core

I am trying to perform a consolidation or merge of migrations on one of many DBContexts.
We have a .NET 6 solution which utilizes several databases. All db contexts have been defined in a single project, in separate folders. I.e.
Solution\
- Business_Logic_Project_1\
- Business_Logic_Project_2\
- Business_Logic_Project_3\
- Database_Project\
- Context1\
- Migrations\
- Models\
- Context1.cs
- Context2\
- Migrations\
- Models\
- Context2.cs
- Context3\
- Migrations\
- Models\
- Context3.cs
- Database_Project.csproj
- Startup_Project
- Startup_Project.csproj
- Solution.sln
I do the following:
I open a command prompt and go to the root of the solution.
I then delete all migrations in the Database_Project\Context2\Migrations.
I then execute this command:
dotnet ef migrations add <<MIGRATION_NAME>> --context Context2 --project Database_Project --startup-project Startup_Project --output-dir Context2\Migrations
I empty the __EFMigrationsHistory table in the database.
Finally, I run this command to finish the consolidation:
dotnet ef database update <<MIGRATION_NAME>> --context Context2 --project Database_Project --startup-project Startup_Project
This fails with the error message: The migration '<<MIGRATION_NAME>>' was not found.
So, I think this is because the migrations are placed under the context folders, and the database update command do not look that deep. There doesn't appear to be a way of telling the command where to look for migrations though, so what to do?

Hard to pinpoint the exact reason but, while providing the migration name in update command, did you include the .cs extension? If so, please try without that.
Other possibilities include
some typo in the command
missing migration designer files

Well, I figured it out, but I forgot about this question, so I can't remember the issue and how I solved it.
However, I found that these steps works:
Step 1: Delete all *.cs files under the Migrations folder. Except the *ModelSnapshot.cs.
Step 2: Copy all records from the __EFMigrationHistory to the __EFMigrationHistoryBackup:
INSERT INTO dbo.[__EFMigrationHistoryBackup] (MigrationId, ProductVersion)
SELECT MigrationId, ProductVersion FROM dbo.[__EFMigrationsHistory]
Step 3: Empty the __EFMigrationHistory table:
DELETE FROM dbo.[__EFMigrationHistory]
Step 4: Create a new migration like: dotnet ef migrations add Migration_Merge_2022Q4.
Both the Up() and Down() methods of the migration should be empty. If not, comment out all code inside the two methods.
Step 5: Update the database like: dotnet ef database update. This should add a new record in the __EFMigrationHistory table, but since Up() and Down() is empty, no changes is made to the database.
Step 6: Uncomment the Up() and Down() methods.
Step 7: Check the changes into Git.

Related

Change table name related to entity model

I have some data in my database in a table called "Test".
I've made a duplicate of that table called "CopyTest".
If i change:
modelBuilder.Entity<IISLog>()
.ToTable("Test");
to:
modelBuilder.Entity<IISLog>()
.ToTable("CopyTest");
I get an error saying:
context has changed since the database was created. Consider using
Code First Migrations to update the database
How can i stop this from showing? It's just a table name change :)
Solution 1:
Delete First Migration and than try:
Add-Migration <migration-name>
Then open Migration file and change Table Name Manually. After that:
update-database -verbose
If it not works.
Solution 2:
Try to delete Migration History from SQL server Management studio .
Reference URL - Resetting Entity Framework Migrations to a clean Slate
Migrate to the initial DB
with
Update-Database -TargetMigration:"name_of_migration"
then update to your current state:
Update-Database
if necessary add your migration again:
Add-Migration TableNameUpdate
Add a new migration using add-migration Rename_Test_To_CopyTest
Then, in the resulting file, use the RenameTable method:
public partial class Rename_Test_To_CopyTest : DbMigration
{
public override void Up()
{
RenameTable("dbo.Test", "dbo.CopyTest");
}
public override void Down()
{
RenameTable("dbo.CopyTest", "dbo.Test");
}
}
Then use update-database as usual.

What are the rules for expected values to the dotnet ef commands?

In an ASP.NET Core application with migrations, running update database gives the following output. It works, and the verbose output displays the default values for a variety of options.
dotnet ef --verbose database update
Setting the data directory to 'C:\temp\bin\Debug\netcoreapp1.0\'.
Invoking dependency command 'Microsoft.EntityFrameworkCore.Design' in project '2016-101DP-TreeGame-Auth'
Running C:\Program Files\dotnet\dotnet.exe exec
--runtimeconfig C:\temp\bin\Debug\netcoreapp1.0\temp.runtimeconfig.json
--depsfile C:\temp\bin\Debug\netcoreapp1.0\temp.deps.json
--additionalprobingpath C:\Users\me\.nuget\packages C:\Users\me\.nuget\packages\Microsoft.EntityFrameworkCore.Design\1.0.0-preview2-final\lib\netcoreapp1.0\Microsoft.EntityFrameworkCore.Design.dll
--assembly C:\temp\bin\Debug\netcoreapp1.0\temp.dll
--startup-assembly C:\temp\bin\Debug\netcoreapp1.0\temp.dll
--dispatcher-version 1.0.0-preview2-21431
--data-dir C:\temp\bin\Debug\netcoreapp1.0\
--project-dir C:\temp
--content-root-path C:\temp
--root-namespace temp
--verbose update database
Process ID: 12544
Finding DbContext classes...
Using context 'ApplicationDbContext'.
Done.
When I try to run the same command with options, the CLI complains that my options have "unexpected values." Here are two examples.
dotnet ef --data-dir C:\temp\bin\Debug\netcoreapp1.0\ --verbose database update
dotnet ef --data-dir "C:\temp\bin\Debug\netcoreapp1.0\" --verbose database update
Both tell me this:
Microsoft.Extensions.CommandLineUtils.CommandParsingException: Unexpected value 'C:\temp\bin\Debug\netcoreapp1.0\' for option 'data-dir'
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at Microsoft.EntityFrameworkCore.Tools.Cli.Program.Main(String[] args)
What are the rules for expected values to the dotnet ef commands?
There are two layers. dotnet-ef reads metadata from the project (and builds it) then calls ef using that metadata (including the output assembly paths). You cannot specify the following options from dotnet ef since they are determined for you.
--assembly
--startup-assembly
--data-dir
--project-dir
--content-root-path
--root-namespace
The rest of the options that show up in dotnet ef --help can be specified on dotnet ef.
This should get better as part of issue #6592.
Here is some documentation about dotnet ef.

Updating database table & column

Using MVC4 and EF Code First
I renamed my table/column-name i.e. table: from Categories to Category in the model and in the code and when I run the migration statement
Update-Database -Verbose -Force
I get an error:
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'dbo.Categories' and the index name 'PK_dbo.Categories'. The duplicate key value is (). Could not create constraint. See previous errors. The statement has been terminated.
In the configuration file I have AutomaticMigrationsEnabled = true;
Is there something else I need to do to make the changes apply in the database?
You cannot modify the PK.
1 - Delete existing database then run Update-Database
2 - Generate update script by running Update-Database -Script and add drop index TSQL to generated file and run the script.
3 - Remove key constrain from table via Visual Studio or Management Studio then remove TSQL for dropping index in generated script then run script.

Entity Framework: Add-Migration fails with Unable to update database

I have been using Entity Framework (5.0) for a while now in a project (ASP.NET MVC in VS2012 Express). Right now, though, I am no longer able to add migrations.
PM > Add-Migration -projectName MyProject.DAL TestMigration
Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
I do not know if this gives any clue but the 'Unable to ..." text is displayed in red.
I have tried to enable automatic migration (which makes no sense as I am trying to write the pending model changes to a code-based migration) and that results in the required migration in the database. However this is not what I want because I then I do not have a migration in the project.
I have tried to remove the database and recreate the database. The database is recreated (up to the previous migration) but when I then try to use the Add-Migration I still get the "Unable to update.." error.
Edit
I tried the -force parameter but with no difference.
The contents of my configuration class (I did not change anything after the previous migration):
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(Bekosense.DAL.Context.BekosenseContext context)
{
context.Database.ExecuteSqlCommand(Properties.Resources.TriggerAlertMessageDrop);
context.Database.ExecuteSqlCommand(Properties.Resources.TriggerAlertMessageCreate);
context.Database.ExecuteSqlCommand(Properties.Resources.TriggerAlertMessageSentDrop);
context.Database.ExecuteSqlCommand(Properties.Resources.TriggerAlertMessageSentCreate);
context.Database.ExecuteSqlCommand(Properties.Resources.AddDbUsers);
}
Edit 2
I found out that I am able to do an add-migration when I comment the following line out in my DbContext:
//Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());
when I leave the line above active and comment out everything in the Configuration file, it still won't work.
Why is the Database.SetInitializer line causing this strange behaviour?
You can reset the entity framework to solve your problem [But keep it mind it will bring the Migration to the default state]
Note: To take a backup before performing the following
You need to delete the present state:
Delete the migrations folder in your project
Delete the __MigrationHistory table in your database (may be under system tables)
You will find the __MigrationHistory table in your database [Under App_Data Folder]
Then run the following command in the Package Manager Console:
Enable-Migrations -EnableAutomaticMigrations -Force
Use with or without -EnableAutomaticMigrations
And finally, you can run:
Add-Migration Initial
This may also help you
Never use automigrations, that gave me problems in the past (when migrating the database down, use the correct way to do it from the start!)
This line should be in your global.asax:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());
And not in your DbContext!
Other tips if the above won't help:
Perhaps you have multiple layers in your application:
Add-Migration 000 -StartupProjectName "NameOfTheProjectInSolutionExplorer" -ConfigurationTypeName "MyConfiguration" -ConnectionString "theconnectionstring;" -ConnectionProviderName "System.Data.SqlClient" -Verbose
Above is the Add-Migration command i use for a multi-layered application.
Same thing for an update of the database
Update-Database -ConfigurationTypeName "SlaveConfiguration" -StartupProjectName "FacturatieMVCv2.Data" -Verbose -script
In my case I've got the same error because I was forcing ObjectContext.CommandTimeout on class DbContext at constructor method during migration.
Try removing it
((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 5000;
This worked for me:
update-database -targetmigration:"0" -force -verbose
add-migration Initial
update-database

Strategy for Getting SQL for AutomaticMigrations

We're using EF 5RC, code first with migrations. I feel like this should be an easy question to answer (i hope). Is there a good way to figure out what the automatic migration is attempting to do.
I've added a migration through the Add-Migration PS command.
I've invoked Update-Database and all seems fine with that migration.
Now - I'm just running Update-Database like i normally do, but with the following error:
PM> update-database -Verbose
Using StartUp project 'Web'.
Using NuGet project 'DataAccess'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'UserGroup' (DataSource: (localdb)\v11.0, Provider: System.Data.SqlClient, Origin: Configuration).
No pending code-based migrations.
Applying automatic migration: 201206301526422_AutomaticMigration.
Automatic migration was not applied because it would result in data loss.
Notice, i'm adding the -Verbose option, and I've tried it again with the -Script. But I have no idea what we're migrating to; and what SQL - or what it thinks will result in data loss.
I do not want to simply enable "allow data loss" here, but am trying to understand how to troubleshoot these migrations.
Thank you in advance!
Just run:
PM> Update-Database -Script -Force
This will generate the SQL and display it in a window without running it.
I got this error on Azure after a publish , but there u cant use -Force , so global solution (and no need for -Force on local too )
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true; // <-- THIS LINE
}