I have just created a database and done my first migration (just a simple table add). Now I want to add some stored procedures which I have just added by writing the sql and executing it in Management Studio. But I would like to include these stored procedures if possible in a migration so that they are saved and I can run an Up or Down method against them. Is this possible and if so what syntax needs to be used? Or will I just have to add/edit/remove them using Management Studio?
To use a Stored Procedure with the Code First model, we need to override the OnModelCreating method of DBContext and add the following code to map the Stored Procedure. The MapToStoreProcedures method has two overloaded methods, one method is without a parameter.
Run the Add-Migration InitialCreate command in Package Manager Console. This creates a migration to create the existing schema. Comment out all code in the Up method of the newly created migration. This will allow us to 'apply' the migration to the local database without trying to recreate all the tables etc.
Code First Migrations is the recommended way to evolve your application's database schema if you are using the Code First workflow. Migrations provide a set of tools that allow: Create an initial database that works with your EF model. Generating migrations to keep track of changes you make to your EF model.
If you need to deploy the stored procedure as part of migrations you need to create an empty migration first, modify the Up and Down methods and execute it. So first you need to create an empty migration. You can do this with command dotnet ef migrations add GetAllTodoItemsByStatusProc .
I've done this like so...
In the current migration class -
public partial class MyMigration : DbMigration { public override void Up() { ... other table creation logic // This command executes the SQL you have written // to create the stored procedures Sql(InstallScript); // or, to alter stored procedures Sql(AlterScript); } public override void Down() { ... other table removal logic // This command executes the SQL you have written // to drop the stored procedures Sql(UninstallScript); // or, to rollback stored procedures Sql(RollbackScript); } private const string InstallScript = @" CREATE PROCEDURE [dbo].[MyProcedure] ... SP logic here ... "; private const string UninstallScript = @" DROP PROCEDURE [dbo].[MyProcedure]; "; // or for alters private const string AlterScript = @" ALTER PROCEDURE [dbo].[AnotherProcedure] ... Newer SP logic here ... "; private const string RollbackScript = @" ALTER PROCEDURE [dbo].[AnotherProcedure] ... Previous / Old SP logic here ... "; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With