Changing DeleteBehavior.Cascade to DeleteBehavior.Restrict causes EF Core to drop foreign keys - asp.net-core

ASP.NET Core 2.2 project with Entity Framework Core; I'm performing the first EF Migration to create the database:
Here are my steps:
I run Add-Migration myFirstMigration in Package Manager Console
I manually edit the migration files as well as DbContextModelSnapshot.cs to change all instances of DeleteBehavior.Cascade to DeleteBehavior.Restrict because I just want an error thrown if a row gets deleted/updated which causes a FK constraint violation
I run Update-Database which creates the database in SQL Server
Here is the part that confuses me: If I now do Add-Migration again, a migration is created in which it wants to drop my Foreign Key constraints and re-add them with DeleteBehavior.Cascade.
Why is it doing that? Of course it appears to have to do with setting everything to DeleteBehavior.Restrict, but why?

Related

Entity Framework Core - Cannot drop the index 'TableName.IX_TableName_ColumnName', because it does not exist or you do not have permission

I've tryied but I can't solve this by myself. It happens when I want to add composite key in my table using Entity Framework Core. Add-Migration passes but this error comes after Update-Database:
"Cannot drop the index 'TableName.IX_TableName_ColumnName', because it does not exist or you do not have permission."
How can I solve it? Thank you!

Only the first update-database is working (creates the DB) then update-database does nothing

This is an EF Core, ASP.NET Core 3 Preview 5 project in VS 2019. All is working for
PM>Add-Migration Initial
PM>Update-Database
The SQL Server db created correctly based on MyDbContext and Startup.cs and appsettings.json connection string. (so everything is in place)
However if I change MyDbContext either adding a new DbSet or adding a property to an existing entity and run Update-Database nothing happens. No error message.
What I've tried so far:
Completely clean the project either in VS 2019 either by manually in file system
Exit VS, start VS
Deleting the migration folder in the project and DROP the database in SQL Server and starting from ground zero
The idea behind Migrations is to update the database schema and keep it in sync with your application data models (entities), so that you do not need to drop the database and re-create it again (which would cause data loss).
So whenever you do any changes to the Models/DbContext you need to Add-Migration, then do Update-Database.
For more information about migrations read this.

Entity framework adds initial migration creates the database but not the __MigrationHistory table

In a new code-first asp.net-core project connecting to my SQL-server database. When I run
add-migration MyInitialMigration
a migration file is created, then executed in SQL server creating the database, table structure with fields, indexes, etc. and populating the tables with the seed data from my DBInitialiser. The table __MigrationHistory is not created in the database and the ModelSnapshot.cs file is created. At this point I haven't run
update-database
which from everything I can find, I should need to run before the database, seed data, etc. is actually created. As far as I can tell, I've not got automatic migrations enabled.
Because of this, subsequent migrations aren't applied to the database because the tables already exist, which I'm guessing it figures out by looking for the __MigrationHistory table and not finding any rows in it.
How can I either get the initial add-migration to add the __MigrationHistory table or how do I get the migration to only happen when I enter update-database?
Not sure if it's related, but another project that was migrating fine last week now doesn't work properly. The migration .cs file is created fine, but when it automatically tries to create the database, etc. (when previously I needed to run update-database ) I get the error
Invalid JSON primitive: "C:\\x\\Migrations\\20171108125832_MyInitialMigration.cs",
"metadataFile": "C:\\x\\Migrations\\20171108125832_MyInitialMigration.Designer.cs",
"snapshotFile": "C:\\x\\Migrations\\MyContextModelSnapshot.cs"
}.
which relates to the following command I the migrations .cs file
migrationBuilder.CreateIndex(
name: "IX_tablea_tableID2",
table: "tablea",
column: "tableID2");
which as far as I can tell is identical to the several blocks of code above it which all work fine. I've tried deleting the migration files and database and rerunning the add-migration with the same effect. Each time I delete everything and start again like this, a different index causes the error message, even if it worked the previous time.
Has there been an update which breaks/alters how migrations work that I've missed?
You must have something odd in your code, like calling dbContext.Database.EnsureCreatedAsync(). This will create tables and database, but no migrations.
In previous versions of ASP.NET Core / EF Core (1.x), the Configure method of Startup class would not be executed, when running the EF Core tools (either add-migration in Powershell or dotnet ef migrations add in command line).
In order for the __MigrationHistory Table to be created, the migration must be applied with either dbContext.Database.MigrateAsync() or by database-update/dotnet ef database update.
However, with the new versions the migrations (or the dbContext.Database.EnsureCreated()) will be applied on every EF Core tools command.
The new pattern for performing DbContext discovery is to have a BuildWebHost static file, which configures the whole application and have extension methods in Main(...) method to perform the migration and seeding.
My previous answer on the new way to apply migrations (and seeding) covers the code.
The ASP.NET Core Annoucement documents this changes (its always a good idea to subscribe to this GitHub repository to receive notifications about new features and breaking changes)

There is already an object named AspNetRoles in the database. (entity-framework-core)

I have an asp.net core mvc website using entity framework core.
I don't know how it initially happened, but I can't get past the error:
"There is already an object named AspNetRoles in the database"
I ended up deleted the database, deleting all my migration .cs files and starting from scratch.
I've then tried
add-migration MyInitialMigration
same error
I then deleted the database again, and tried a direct
update-database
(without adding a migration)
still the same error
I tried changing the appsettings config string to point to a new, non-existing database.
Still the same error!
Previously on MVC5/EF6 I've encountered this error and have resolved it using the same method as this answer:
There is already an object named in the database
-Add-Migration Initial -IgnoreChanges
However -IgnoreChanges is unsupported in EFCore
Or previously on EF6 I've resolved it by adding a migration, then deleting everything in the Up/Down and running an empty migration. This has not worked on EFCore
How can I continue? I've checked the migration table and they're always empty even though it's created the whole database each time. Just doesn't seemed to have logged it in the migrations table
Found my issue.
I had followed this tutorial to load appsettings from EntityFramework:
https://docs.asp.net/en/latest/fundamentals/configuration.html#example-entity-framework-settings
In the EntityFrameworkConfigurationProvider there is a public override void Load() which has a dbContext.Database.EnsureCreated(); and a CreateAndSaveDefaultValues
Between the two of those it looks like it was initializing the database without tracking the migration.
I commented those out, ran a migration and it worked fine. Hopefully I don't have to comment them out every time I want to run a migration :/
This error happened after I changed my database (I stopped using MSSQLLocalDB and started using Sql Server from the production table).
Here is what I did to make it work :
Deleting the migrations folder
Commenting the last changes I wanted to apply
Calling the Add-Migration command : Add-Migration InitialDbChange
Commenting all the commands inside the Up method of the migration file created (keeping only the content of the Down method)
Calling the update-database command : update-database
I have a now a clean Migration from my database. Now my futur changes will be from this baseline.
Found the solution from this link : https://cmatskas.com/ef-core-migrations-with-existing-database-schema-and-data/
I've just had the same issue, and seems like Database.EnsureCreated() doesn't use migrations, you can use Database.Migrate() instead which is what I've just tried and seems to work, but time will tell when I try another migration.
If you're like me and you pull a copy of your production database to work on in development, make sure all of the migrations in your Migration folder are listed in the __EFMigrationsHistory table of your database. If you move the schema to the production database after your development is complete, you're probably not moving the migrations from that table over to your production database. If any of the migrations in your project are missing from that table, EF will try to update the database with any of the missing migrations. In my case, none of the migrations were listed in the database table, so it started by trying to add the initial migration. After adding all of the migrations to the table (except the latest one that I wanted to update the database), EF updated the database correctly.

Reset Entity Framework 7 migrations

I'm using Entity Framework 7 beta 5. I started with the mvc template with user management. I have added several migrations, during my trials.
Now I want to delete my database, create a new initial migration and produce a new clean db with it.
However the dnx ef commands do not have a command that I know of that will facilitate this. How do I proceed?
What exactly do you need support from EF for? Here's what I'd do:
Delete your database
Delete all your migrations
Configure the context to point to your new, clean
database
Run dotnet ef migrations add <initial-migration-name>