How to add stored procedures to Entity Framework Core DbContext?

.net-core c# entity-framework-6 entity-framework-core

Question

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.

1
1
4/3/2020 6:10:30 PM

Accepted Answer

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" });
2
4/3/2020 7:00:58 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow