[英]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.我正在将我的
DbContext
从 EF 6 转换为 EF Core。 In my DbContext
there are stored procedures defined as such:在我的
DbContext
中有这样定义的存储过程:
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?如何在 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
.从我目前看到的情况来看,似乎需要在每个方法中创建我的上下文的新实例并将
ObjectParameter
转换为SqlParameter
。
EF Core provides the following methods to execute a stored procedure: EF Core 提供了以下方法来执行存储过程:
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示例 ExecuteSqlCommand
var context = new SchoolContext();
context.Database.ExecuteSqlCommand("CreateStudents @p0, @p1", parameters: new[] { "Bill", "Gates" });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.