Entity Framework Core Series Tutorial-24-Using stored procedures

Use stored procedures in Entity Framework Core

Here, you will learn how to execute database stored procedures in Entity Framework Core.
EF Core provides the following methods to execute stored procedures:

  1. DbSet<TEntity>.FromSql()
  2. DbContext.Database.ExecuteSqlCommand()

There are some restrictions on using the FromSql or ExecuteSqlCommand method to execute database stored procedures in EF Core2: the
result must be an entity type. This means that the stored procedure must return all the columns of the entity's corresponding table.
The results cannot contain relevant data. This means that the stored procedure cannot execute JOIN to represent the result.
The insert, update, and delete processes cannot be mapped with this entity, so the SaveChanges method cannot call stored procedures for CUD operations.
Before executing the stored procedure in EF Core, let us create the stored procedure in MS SQL Server.
If you follow the database-first method, execute the following script in the local SQL Server database:

USE [SchoolDB]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[GetStudents]
            @FirstName varchar(50)
        AS
        BEGIN
            SET NOCOUNT ON;
            select * from Students where FirstName like @FirstName +'%'
        END
GO

If you follow the code-first method, please follow these steps:

  1. Add an empty migration by executing the following command in NPM (NuGet Package Manager):
Add-migration sp-GetStudents

2. Write the following code in the Up method of the empty migration class in <DateTime> _sp-GetStudents.cs:

public partial class spGetStudents : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        var sp = @"CREATE PROCEDURE [dbo].[GetStudents]
                    @FirstName varchar(50)
                AS
                BEGIN
                    SET NOCOUNT ON;
                    select * from Students where FirstName like @FirstName +'%'
                END";

        migrationBuilder.Sql(sp);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {

    }
}
  1. Execute the following command in the console to create the above stored procedure in the database:
Update-database

This will create the GetStudents stored procedure in the SQL Server database.

Use FromSql to execute stored procedures

As mentioned in the previous chapter, the FromSql method of DbSet can be used to perform raw SQL queries against the underlying database. Similarly, it can be used to execute stored procedures that return entity data, but there are some limitations.
In the database, we can execute the GetStudents stored procedure using the following INPUT parameter values:

GetStudents "Bill"
-- or
exec GetStudents "Bill"

You can execute the SP using the FromSql method in EF Core in the same way as above, as shown below.

var context = new SchoolContext(); 
var students = context.Students.FromSql("GetStudents 'Bill'").ToList();

You can also use C # string interpolation syntax to pass parameter values ​​as shown below.

var name = "Bill";

var context = new SchoolContext(); 
var students = context.Students
                      .FromSql($"GetStudents {name}")
                      .ToList();
//or
//var students = context.Students.FromSql($"exec GetStudents {name}").ToList();

Use the SqlParameter instance to specify the value of the IN or OUT parameter as follows:

var context = new SchoolContext(); 
var param = new SqlParameter("@FirstName", "Bill");
//or
/*var param = new SqlParameter() {
                    ParameterName = "@FirstName",
                    SqlDbType =  System.Data.SqlDbType.VarChar,
                    Direction = System.Data.ParameterDirection.Input,
                    Size = 50,
                    Value = "Bill"
};*/

var students = context.Students.FromSql("GetStudents @FirstName", param).ToList();

You can also specify @ p0 for the first parameter, @ p1 for the second parameter, and so on.

var context = new SchoolContext(); 
var students = context.Students.FromSql("GetStudents @p0","Bill").ToList();

In the above example, @ p0 is used for the first parameter, because named parameters are not yet supported in EF Core.
Note: By default, DbContext will track all entities in the result. If you execute the same stored procedure with the same parameters multiple times, it will execute the same SQL statement each time, but only one result set will be tracked. For example, the following example will execute the GetStudents stored procedure 3 times, but will only cache and track a copy of the result.

var context = new SchoolContext(); 
var list1 = context.Students.FromSql("GetStudents 'Bill'").ToList();
var list2 = context.Students.FromSql("GetStudents 'Bill'").ToList();
var list3 = context.Students.FromSql("GetStudents 'Bill'").ToList();

Use ExecuteSqlCommand () to execute the stored procedure

The ExecuteSqlCommand () method is used to execute database commands in the form of strings. For the number of rows affected by the specified command, it returns an integer.

var context = new SchoolContext(); 

var rowsAffected = context.Database.ExecuteSqlCommand("Update Students set FirstName = 'Bill' where StudentId = 1;");

In the above example, the update command is passed in the ExecuteSqlCommand method. The value of rowsAffected will be 1, because only 1 row is affected by the specified update command.
Similarly, we can execute stored procedures to create, update, and delete commands. Consider the following stored procedure, which inserts a record into the Student table of the database:

CREATE PROCEDURE CreateStudent
    @FirstName Varchar(50),
    @LastName Varchar(50)
AS
BEGIN
    SET NOCOUNT ON;
    Insert into Students(
           [FirstName]
           ,[LastName]
           )
 Values (@FirstName, @LastName)
END
GO

Now, you can execute the above stored procedure:

var context = new SchoolContext(); 

context.Database.ExecuteSqlCommand("CreateStudents @p0, @p1", parameters: new[] { "Bill", "Gates" });

In the same way, you can execute stored procedures for Update and Delete commands.

Published 177 original articles · 61 praises · 170,000 views

Guess you like

Origin blog.csdn.net/xingkongtianyuzhao/article/details/104227979