HOW TO USE the Script-Migration file generated from visual studio for production on an Ubuntu PostgreSQL database? - postgresql

When I write Script-Migration on Visual Studio console, It creates a file called uhftsodk.sql that contains something like this:
CREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" (
"MigrationId" character varying(150) NOT NULL,
"ProductVersion" character varying(32) NOT NULL,
CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY ("MigrationId")
);
I am a Windows user, but the production environment I am trying to implement is an Ubuntu 20.04 vm, with PostgreSQL.
I run this script in PostgreSQL from Ubuntu and it generated the table called "__EFMigrationsHistory"
But, What else am I supposed to do from there?
I want to create all my tables I used in Visual Studio for this particular project. I am using PostgreSQL for both scenarios, and it is working on development (using add-migration name and update-database) but not working in production...

The problem was I deleted the migrations, so when I run Script-Migration from Package Manager Console, it did not create all the tables, just the __EFMigrationsHistory table...
So, I created a new migration again, and then run Script-migration. Now the file was completed.

Take a look at the CLI commands dotnet ef migrations script and dotnet ef database update.
CLI commands can be run in any environment (Windows and Linux). You would generally script the migrations first, then review the script, then test the script, then backup the production database and then apply the script to the production database.
If this does not answer your question, please go into more details, where the problem for you lies. (The question has been asked a bit vague.)

Related

EF Core Migration problem with updating a server

Locally my database works fine. I try to put a server database to the same version as my development version.
In Visual Studio, I ran this command:
dotnet ef migration scripts lasknown_script_that_was_executed_on_prod_server
where I use the value of
lasknown_script_that_was_executed_on_prod_server
as found on the production server by querying:
SELECT TOP 1000
[MigrationId], [ProductVersion]
FROM
[MyProject].[dbo].[__EFMigrationsHistory]
and yes it's in my source code as well, so seems OK, my code knows that version.
After I perform that command, it creates a large output but on top of that it shows an error
Build started...
Build succeeded.
Error writing app settings | Cannot perform runtime binding on a null reference
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 6.0.5 initialized 'ApplicationDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer:6.0.5' with options: > None
BEGIN TRANSACTION;
GO
CREATE TABLE [MyApplication] ( ...my firs db create..?? ...
I assume therefore the output code is missing something that should go before the very first initial database creation.
(as my prod server is not at that version, it shouldn't start with the first migration).
Locally it works fine, however, and it was set up with code-first.
So it was generated by code, it should migrate as well by code.

"Update Model from Database" as build step

I am working on an application that utilizes a database that often has tables added to it or modified. Is there a way I can regenerate the .edmx file as a build step or during compile time to add these new tables/modifications without manually running the wizard?
You can try to run sql scripts to insert/modify tables during build process.
Related extension:
ExecuteSqlScript
Run SQL Server Scripts Task
Or directly use PowerShell to Execute .SQL Files from Directory.
Reference below articles to change the database during build/release:
Build​ ​and​ ​Release​ ​Process​ ​for​ ​SQL​ ​Server​ ​Database​
​Scripts​ ​using​ ​Online​ ​TFS​
Continuous Deployment of SQL Server Database Changes using Visual
Studio & TFS Release Manager
UPDATE:
Choosing the Update Model from Database is the best method for updating your EDMX. There are certain properties that don't get updated on the Conceptual layer.
See How do you update an edmx file with database changes?
Seems there isn't a good way to achieve that, however if the actions can be executed in command line, then we can add a step to run the command or script.

Entity Framework Core: Script-Migration not recognizing migrations when creating script

I've got a full .NET Framework 4.6.2 Web API app that I've installed Entity Framework Core 1.1.2 into. It contains some classes, a DbContext class and has the relevant EF Core NuGet packages installed.
When I run Add-Migration Initial in the package manager console within Visual Studio, it correctly identifies the DbContext in the project and produces the migration class as well as a snapshot. The migration looks correct, given that within the Up method, it shows a number of create tables for each of the classes I want, it shows the expected columns for each and the constraints I'd expect, so that looks good. Also, within the Down method, it drops all the tables (which makes sense since this is the first migration done). This migration class is created in the /Migrations directory within the project.
When I run Script-Migration in the console next, it produces a SQL script that is incorrect, in that it only creates the table for the EFMigrationsHistory, as follows:
IF OBJECT_ID(N'__EFMigrationsHistory') IS NULL
BEGIN
CREATE TABLE [__EFMigrationsHistory] (
[MigrationId] nvarchar(150) NOT NULL,
[ProductVersion] nvarchar(32) NOT NULL,
CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY ([MigrationId])
);
END;
GO
This SQL file is created in the bin/Debug directory for the project.
I would expect that the output of this Script-Migrations command contain the SQL version of the Up method in the migration class that was produced by the previous Add-Migrations Initial command, but alas, this is not the case. If I run Update-Database, it runs against this SQL file and continues to ignore the existing Migrations.
Similarly, this appears to be a larger issue with EF Core, because if I attempt to do a Remove-Migration as suggested in the console after running Add-Migration, it is also unable to find the Migration it just produced and gives me the following error:
No ModelSnapshot was found.
And I know this can't be the case because I see it right there in the Migrations folder along with the initial migration class it created.
What's going on and is there any known workaround to get these tools working appropriately?
Update
While testing, I've found that if I create a new solution with just these few parts in it, it works fine. However, in my original solution, I have these projects within a number of solution folders, so perhaps that's the issue at hand, because putting the new project in a solution folder causes the same issues observed in the rest of this question.

asp core ef migrations on production server

Can't perform migrations on production server.
Command "dotnet ef database update" works on my computer but fails on production
Steps i tried are:
1. Fill in checkbox execute code first migrations in Visual Studio before publish.
2. dotnet ef database update not working . I installed .NET SDK but it doesn't have libraries needed.
Any suggestions appeciated.
There are a couple options:
Generate a SQL script using dotnet ef migrations script and run it on your production database.
Call dbContext.Database.Migrate() at runtime during application startup (but be careful when running multiple apps/database clients)
Also, in the next release (1.0.0-preview3) of Microsoft.EntityFrameworkCore.Tools, we'll be shipping ef.exe which you can point directly to assemblies (instead of project.json files) to perform migrations.
You can generate a migration script by running the following command:
Script-Migration -From older_migration_name -To newer_migration_name -Context ApplicationDbContext
The script will have a random name and will reside in the following path:
<Your_Project_Drive>:\<Your_Project_Folder>\<Your_Project_Folder.Model>\obj\Debug\netcoreapp3.1\<Some_Random_Name>.sql
Now just run that script on the targeted DB of production server.

How to Manage EF Migrations Between Development and Production Databases?

Before anyone marks this as a duplicate, none of the questions similar to this addressed any of my concerns or answered any of my questions.
I am currently developing all the POCOs and data contexts in a library project, and running migrations from within this project. The database I'm updating is the development database.
What do I do if I want to create the current schema to a fresh, new database? I figure that all I have to do is to change the connection string in web.config and run Update-Database, correct?
While the live/production database is up and running, I want to add new columns and new tables to the schema, and test it out in development. So I switch back the connection string to the development database's connection string, and run Update-Database.
Going back and forth between two databases seems like I'll get conflicts between _MigrationHistory tables and the auto-generated migration scripts.
Is it safe to manually delete the _MigrationHistory tables in both databases, and/or delete the migration files in /Migrations (so I'll run Add-Migration again)? How do we manage this?
What do I do if I want to create the current schema to a fresh, new database?
- Yes, to create fresh database to the current migration level you simply modify the connection string to point to a database that does not yet exist and run update-database. It will run all the migrations in order.
As far as migrating to the Production database, I am running the update-database command with the -script switch to acquire the raw sql and then applying that script to the production database manually. This is helpful if you need to keep a record of sql commands run against the database as well. Additionally, you can generate the script explicitly from a specific migration to another specific migration via some of the other update-database switches.
Alternatively, you can create an Idempotent script that works from any migration by using the–SourceMigration $InitialDatabase switch and optionally specify an end migration with –TargetMigration
If you delete the _MigrationHistory tables you will have issues where the generated script will be trying to add columns that already exist and such.
You may find the following link helpful:
Microsoft Entity Framework Migrations
I would suggest having a separate trunk in your source code repository - one pointing to production and one to development to avoid risks of switching between the two in visual studio.
Me also had the same problem, even when using one and the same database - due to some merges in the repository, and the mix of automatic/manual migrations. For some reason the EF was not taking into account the target database, and calculating what scripts need to me executed, based on what is already in the database.
To fix this, I go to the [__MigrationHistory] table on the target database and get the latest migration name. This will help EF to determinate the state of the DB, and will execute just the scripts needed.
then the following script is run:
update-database -script -sourcemigration {latest migration name}
This creates update script that is specific to the target database (the connection string should be correct, as discussed in the other comments)
you can also use -force parameter if needed
this way you can update any database to latest version, no mater in what version you found it, if it has MigrationHistory table.
Hope this helps
My production and my developmental database went out of synch and it gave me endless problems. I solved it using a tool from Red-Gate to match up the databases. After using the tool, the databases were exactly the same but my migration was not working and I started to get odd errors i.e. trying to add tables/ columns that already existed etc. I solved that. I just deleted the migration folder on the local, recreated it, added the initial migration, updated the database and then matched the data of this migration file (local) to the one on the host (delete all the data in the migration file on the host, and add the same data that is on the local into the host). A more detailed explanation is at:
migration synch developmental and production databases