How can I call a SQL Stored Procedure using EntityFramework 7 and Asp.Net 5

后端 未结 5 518
夕颜
夕颜 2020-11-29 10:48

For last couple of days I am searching for some tutorials about how to call a Stored Procedure from inside a Web API controller method using

5条回答
  •  忘掉有多难
    2020-11-29 11:08

    For Database first approach , you have to use Scaffold-DbContext command

    Install Nuget packages Microsoft.EntityFrameworkCore.Tools and Microsoft.EntityFrameworkCore.SqlServer.Design

    Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
    

    but that will not get your stored procedures. It is still in the works,tracking issue #245

    But, To execute the stored procedures, use FromSql method which executes RAW SQL queries

    e.g.

    var products= context.Products
        .FromSql("EXECUTE dbo.GetProducts")
        .ToList();
    

    To use with parameters

    var productCategory= "Electronics";
    
    var product = context.Products
        .FromSql("EXECUTE dbo.GetProductByCategory {0}", productCategory)
        .ToList();
    

    or

    var productCategory= new SqlParameter("productCategory", "Electronics");
    
    var product = context.Product
        .FromSql("EXECUTE dbo.GetProductByName  @productCategory", productCategory)
        .ToList();
    

    There are certain limitations to execute RAW SQL queries or stored procedures.You can’t use it for INSERT/UPDATE/DELETE. if you want to execute INSERT, UPDATE, DELETE queries, use the ExecuteSqlCommand

    var categoryName = "Electronics";
    dataContext.Database
               .ExecuteSqlCommand("dbo.InsertCategory @p0", categoryName);
    

提交回复
热议问题