简体   繁体   中英

How to add stored procedures to Entity Framework Core DbContext?

I am in the process of converting my DbContext from EF 6 to EF Core. In my DbContext there are stored procedures defined as such:

public virtual ObjectResult<Nullable<int>> StoredProcedureOne(Nullable<int> maxValue, Nullable<int> minValue)
{
    var maxValueParameter = maxValue.HasValue ?
            new ObjectParameter("MaxValue", maxValue) :
            new ObjectParameter("MaxValue", typeof(int));

    var minValueParameter = minValue.HasValue ?
            new ObjectParameter("MinValue", minValue) :
            new ObjectParameter("MinValue", typeof(int));

    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Nullable<int>>("StoredProcedureOne", maxValueParameter, minValueParameter);
}

How can I define a stored procedure in EF Core? All the examples I could find are stored procedures for a specific entity. From what I've seen so far it looks like need to create a new instance of my context in each method and convert the ObjectParameter to SqlParameter .

EF Core provides the following methods to execute a stored procedure:

  1. DbSet.FromSql()
  2. DbContext.Database.ExecuteSqlCommand()

Example:

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();

Example ExecuteSqlCommand

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM