Entity framework adds initial migration creates the database but not the __MigrationHistory table - asp.net-core

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)

Related

Generating script for multiple Contexts, with database reference, in Entity Framework Core

I have been able to successfully create multiple DBContexts within my ASP.NET Core application that connect to multiple tables in multiple databases.
After creating my first migrations for both contexts, I'm able to generate my SQL scripts using the command:
Script-Migration -Context CustomContext1
Script-Migration -Context CustomContext2
When I looked at the result of the script generation, I noticed that both scripts for both contexts don't reference the database of either CustomContext1 or CustomContext2. I'm supposed to send this script down an automated pipeline, which means that the specif DB for each script needs to be included.
How do I get this to happen automatically using the script generation command?
After so many days of research and testing, the only way to accomplish this is to manually add the "USE Database" line to the beginning of the generated SQL script.
It makes no sense, really. With the presence of multiple DbContexts, the logical thing to do when SQL scripts are being generated would be to automatically add the "USE Database" line at the beginning of each script.
Perhaps a fix will be included in the next version of EF Core tools. Who knows.

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.

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.

Entity Framework DB Migration Script

Okay, so this is my situation. I have generated POCOs from a db and developed around them. I have also renamed and changed some of these POCOs to be more readable. I have now made changes to my original db scheme and need to migrate the changes back to my models without overriding my changes except where the scheme has changed. It there a way to generate a *.sql script to hand to by DBAs? If so, it there a way to compare two dbs and generate a change script? ie - dev db => prod db.
You can switch a project to code first and generate the scripts you need via migrations. See the link below for a guide on moving from db first to code first, but it sounds like you may be partially there already.
1) enable-migrations for the project with your context if you haven't already.
2) create a baseline migration. EF will use this as a starting point so you won't get a bunch of code to create the objects that already exist. The ignore changes flag tells EF not to create the existing objects. https://msdn.microsoft.com/en-us/data/dn579398.aspx?f=255&MSPPError=-2147217396#option1
create-migration InitialCodeFirst -IgnoreChanges
3) Now modify your schema as you normally would and create a migration:
add-migration SomeNewThing
4) Create a script for a different database (like PROD) by using -Script. This will not update your database it just creates a script, so I usually run it a second time without -Script:
update-database -Script // creates a script (in VS), but does not apply
update-database // updates the database your connect string points to
5) DBA runs script and this will add a record to __MigrationHistory to identify it as being applied.
http://devgush.com/2014/02/24/migrating-a-project-from-database-first-to-code-first/
Here is a useful link on deployment: http://cpratt.co/migrating-production-database-with-entity-framework-code-first/#at_pco=smlwn-1.0&at_si=54ad5c7b61c48943&at_ab=per-12&at_pos=0&at_tot=1

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>