OiO.lk Blog SQL Defining the target database with Entity Framework migration script generation
SQL

Defining the target database with Entity Framework migration script generation


Generating script with Entity Framework requires the script to be run on a specific database. In our setup, we want our database administrators to run the script, but at the same time we want to ensure that the script is not executed on an unintended database. This is easily achieved by starting the script with USE <DatabaseName>;.

I’ve read through the migration script generation documentation for Entity Framework, but I have not been able to find a solution as to how we can ensure the script starts with the aforementioned.

Example

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

BEGIN TRANSACTION;
GO

IF NOT EXISTS (
    SELECT * FROM [__EFMigrationsHistory]
    WHERE [MigrationId] = N'20241014074159_Init'
)
BEGIN
    CREATE TABLE [Causes] (
        [Id] uniqueidentifier NOT NULL,
        [Tag] nvarchar(100) NOT NULL,
        [Title] nvarchar(250) NOT NULL,
        CONSTRAINT [PK_Causes] PRIMARY KEY ([Id])
    );
END;
GO

...

Wanted result

The script change I’m searching for would result in the following:

USE [SomeDatabase]; -- Specify target database
GO

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

Is there any way I can define this using dotnet ef tool, combined with the command migrations script?



You need to sign in to view this answers

Exit mobile version