3

In EF Core, we can add the tables using entity classes. Stored procedure is one of the useful component. So is there any way to create a stored procedure from the DbContext class (just like Using Dbset we can create the tables)?

Have gone through some links where in the EF6 there is a way to push the stored procedure, although its an workaround it seems.

Reference Link--> EF 6 code-first with custom stored procedure

Although I followed the above link, it means for EF6, where the migration files were inherited from DbMigration, in EF Core it's a Migration base class. I don't see a way & probably didn't find much article related to it.

Any help or suggestions?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
lokanath das
  • 736
  • 1
  • 10
  • 35

3 Answers3

2

Under normal circumstances, we use MigrationBuilder.Sql method in the Up method of your migration class to create a stored procedure, like below:

public partial class SPCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
    //...

    var sp = @"CREATE PROCEDURE [dbo].[GetStudents]
        AS
        BEGIN
            select * from Students
        END";

    migrationBuilder.Sql(sp);
}

protected override void Down(MigrationBuilder migrationBuilder)
{
    //...
}
}

To execute a stored procedure, you can call FromSqlRaw method, like this:

var students= _dbcontext.Students.FromSqlRaw("EXECUTE GetStudents").ToList();
Yinqiu
  • 6,609
  • 1
  • 6
  • 14
0
public partial class SPCreate : Migration
{
   protected override void Up()
   {
       Sql(@"CREATE PROCEDURE [dbo].[GetStudents]
          AS
          BEGIN
              select * from Students
          END");
    }

    protected override void Down()
    {
  
    }
}
//Calling on code 
List<Customer> list;
string sql = "EXEC GetStudents";
list = _context.Database.SqlQuery<Student>(sql).ToList();


List();
-1

Like the normal situation add a migration with a command like bellow:

Add-Migration "Migration Name"

Then in the Up section add as follows:

protected override void Up(MigrationBuilder migrationBuilder)
{
    var assembly = Assembly.GetExecutingAssembly();
    var resourceNames = assembly.GetManifestResourceNames().
        Where(str => str.EndsWith(".sql"));
    foreach (string resourceName in resourceNames)
    {
        using (Stream stream = assembly.GetManifestResourceStream(resourceName))
        using (StreamReader reader = new StreamReader(stream))
        {
            string sql = reader.ReadToEnd();
            migrationBuilder.Sql(sql);
        }
    }
}

This code finds all resources that end in “.sql” and runs each of them.

To make the SQL scripts embedded resources, you can just edit the .csproj file and make sure they are included like following:

<ItemGroup>
    <EmbeddedResource Include="SQL\{YourSqlFileName}.sql" />
    ...
</ItemGroup>

And finally run update database command as usual

Najib
  • 500
  • 2
  • 8