code-snippets/docs/ef-core/stp-migration.md
Liam Pietralla 8ad5845efc
Some checks failed
Build, Test & Publish / Build and Publish Container Image (push) Has been cancelled
Build, Test & Publish / Deploy to Infrastructure (push) Has been cancelled
Build, Test & Publish / Build (push) Has been cancelled
initial commit
2024-09-05 13:54:08 +10:00

1.8 KiB

sidebar_position
1

Adding Stored Procedures to a Migration

Sometimes even when working with an ORM like Entity Framework Core, you need to use a stored procedure. This is especially true when you are working with legacy databases or you need to have performant and consise SQL.

Add Migration

The first step is to add a migration to your DB Context:

::: code-group

dotnet ef migrations add AddUserStoredProcedure
Add-Migration AddUserStoredProcedure

:::

This will add a migration file similar to the following:

public partial class AddUserStoredProcedure : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {

    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {

    }
}

Add Stored Procedure

The stored precedure can then be added using the Sql method on the MigrationBuilder object. The following example shows how to add a stored procedure that returns a user by their ID:

public partial class AddUserStoredProcedure : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.Sql(@"
            CREATE PROCEDURE [dbo].[GetUserById]
            @Id int
            AS
            BEGIN
                SET NOCOUNT ON;
                SELECT * FROM [dbo].[Users] WHERE [Id] = @Id
            END
        ");
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.Sql(@"
            DROP PROCEDURE [dbo].[GetUserById]
        ");
    }
}

Update Database

Once the migration has been added, you can update the database using the following command:

::: code-group

dotnet ef database update
Update-Database

:::