How to call a simple stored procedure in ASP.NET Core 2.0 MVC

2.9k Views Asked by At

I just want to call the stored procedure from ASP.NET Core 2.0 MVC.

I see this type of question many times but every question containing some parameters or calling any by the individual table.

But nothing that is in use for me.

Because just I want to call the stored procedure so the whole function will be done by the stored procedure only.

But I am don't know how to call special stored procedure by the controller.

Here is my stored procedure:

create procedure dbbackup
    @BackupSQLScript nvarchar(max),
    @SQLBackupFileName nvarchar(max),
    @DatabaseName sysname,
    @SQLBackupFolder nvarchar(400)
as 
begin
    set @DatabaseName = 'SQL Database'
    set @SQLBackupFolder = 'D:\'

    set @SQLBackupFileName = replace(@DatabaseName, ' ', '-') + convert(varchar, getdate(), 112) + '.bak'

    set @BackupSQLScript = 'BACKUP DATABASE [' + @DatabaseName + ']
                            TO DISK = ''' + @SQLBackupFolder + @SQLBackupFileName + ''''

    print @BackupSQLScript

    exec sp_executesql @BackupSQLScript
end

Just I call this stored procedure from the controller.

1

There are 1 best solutions below

0
Cujoey On

First Create a class with empty body, but .Net Core may complain about the class not having a primary key so you can add one property decorated with [Key]

public class simple {
  [Key]
  public int nothing {get; set;}
}

Then in your dbContext class add it to your DbSet declarations

public virtual DbSet<simple> Simple { get; set; }

Then in your controller, you simply do this

public IActionResult SimpleProcedure()
{
   var q = dbcontext.Simple.FromSql("exec dbBackup");
   return OK(q);
}