EF Core 2.0.1 - Entity framework migration specific update - minus out initial database update


Wow, this title is pretty long.

Let's say you already have an existing database and right now you wanted to use EF Core to help migrate specific DML updates to your target database - which could be creating a new View or creating additional table minus out the initial database structure.

Note : Sometimes when you do an upgrade, you might get error message saying "your database has already been updated".


All rite, to be honest, you ca't do specific migration, example you can say "apply ABC Migration".

It is all based on the migration class that you've setup in your project,  meaning you get to type "Update-Database" without any parameter.

Anyways, please setup your project and all in the required EF nugets.

Next create the following class.

using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Alphacert.Acc.Ods.Entities.Entities;
[DbContext(typeof(IDS_ODSContext))]
[Migration("AccAppViewMigration1")]
// You must specify this paramater otherwise it will throws and exception because of [__EFMigrationsHistory] data is null
public partial class AccViewMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
// Changes you want to apply //
var operation = migrationBuilder.Sql(@"CREATE VIEW APPTESTVIEW AS SELECT INSTRUMENTID, VALUATIONDATE FROM VWVALUATIONS;");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
// Unfortunately there is no rollback // :)
var operation = migrationBuilder.Sql(@"DROP VIEW APPTESTVIEW;");
base.Down(migrationBuilder);
}
}


Then you specific what needs to be done. In this case, we are creating a view called "AppTesrtView".


Goto "package manager console" and then run "Update-Database". Please note you need to give a name to  [Migration("MyMigrationName")] as shown above. Otherwise you will get an exceptions.

You cannot use " Add-Migration " because it generates the initial database structure which can be complicated to resolve.


Github is available here.




Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20