Search code examples
entity-framework-coreef-code-first.net-6.0

How to create stored procedure in EF Core using .NET 6


I have a class library project in .NET 6 where I am using EF Core. I am able to create tables using the code-first approach, but stuck on how to create stored procedures. I have seen a few articles on Google but it's showing using old EF 6 but not for EF Core.


Solution

  • There is no automatic way to create a stored procedure with EF Core, but the process to do it manually is quite simple.

    First create a new migration as you would normally, it should be empty. Then edit the migration to manually create the procedure. For example:

    public partial class MyNewStoredProcMigration : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql("CREATE PROC DoStuff....");
        }
    
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql("DROP PROC DoStuff");
        }
    }
    

    Note that you may want to move the string for the procedure into a resource file to keep things tidy.