简体   繁体   English

如何首先通过EF代码从存储过程中检索输出参数

[英]How to retrieve output parameter from stored procedure by EF code first

i am new in EF and working with EF code first.我是 EF 的新手,首先使用 EF 代码。 just got a linkhttps://code.msdn.microsoft.com/How-to-retrieve-output-e85526ba which show how to use read output type param by EF db first.刚刚得到一个链接https://code.msdn.microsoft.com/How-to-retrieve-output-e85526ba ,其中显示了如何首先使用 EF db 读取输出类型参数。 so anyone tell me how to retrieve output parameter from stored procedure by EF code first ?所以有人告诉我如何首先通过 EF 代码从存储过程中检索输出参数?

if possible give me small sample code or redirect me to relevant articles.如果可能,给我小示例代码或将我重定向到相关文章。

thanks谢谢

I got a solution我有一个解决方案

var outParam = new SqlParameter();
outParam.ParameterName = "TotalRows";
outParam.SqlDbType = SqlDbType.Int;
outParam.ParameterDirection = ParameterDirection.Output;

var data = dbContext.Database.SqlQuery<MyType>("sp_search @SearchTerm, @MaxRows, @TotalRows OUT", 
               new SqlParameter("SearchTerm", searchTerm), 
               new SqlParameter("MaxRows", maxRows),
               outParam);
var result = data.ToList();
totalRows = (int)outParam.Value;

To retrieve the data for a stored procedure call, you can use the following要检索存储过程调用的数据,可以使用以下命令

using(var db = new YourConext())
{
       var details = db.Database.SqlQuery<YourType>("exec YourProc @p", 
                      new SqlParameter("@p", YourValue));
}

YourType : might be int or string or long or even a ComplexType YourType :可能是 int 或 string 或 long 甚至是 ComplexType

@p : in case if the stored procedure has parameters and you can define as many as you need from parameters @p :如果存储过程有参数并且您可以从参数中定义任意数量的参数

if you need more information about SqlQuery , you might check the following如果您需要有关 SqlQuery 的更多信息,您可以检查以下内容

  1. Writing SQL queries for entities为实体编写 SQL 查询
  2. Entity Framework Code First and Stored Procedures 实体框架代码优先和存储过程

Hope this will help you希望这会帮助你

This way we can also call a stored procedure without using exec command.这样我们也可以在不使用exec命令的情况下调用存储过程。

using (var context = new BloggingContext()) 
{ 
    var blogs = context.Blogs.SqlQuery("dbo.GetBlogs").ToList(); 
}

You can also pass parameters to a stored procedure using the following syntax:您还可以使用以下语法将参数传递给存储过程:

using (var context = new BloggingContext()) 
{ 
    var blogId = 1; 

    var blogs = context.Blogs.SqlQuery("dbo.GetBlogById @p0", blogId).Single(); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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