检索实体框架中的存储过程输出参数始终为null

时间:2013-08-27 15:11:09

标签: c# entity-framework stored-procedures entity-framework-4 output-parameter

C#代码

public List<searchProducts_Result> GetProducts()
{
            var nameParam = new ObjectParameter("numbers", typeof(int));
            List<searchProducts_Result> listobjs = new List<searchProducts_Result>();
            ObjectResult<searchProducts_Result> objResult = null;
            searchProducts_Result outParam = new searchProducts_Result();
            using (var db = new SPWebEntities())
            {
                objResult = db.searchProducts("asd", 2, 5, "15", nameParam);
                if (nameParam.Value != null)
                    outParam.UserID = nameParam.Value.ToString();
                else
                    outParam.UserID = "0";
               listobjs.Add(outParam);
                foreach (searchProducts_Result sr in objResult)
                {
                    listobjs.Add(sr);
                }
            }

            return listobjs;
}

我的存储过程:

[searchProducts]
    @productName varchar(50),
    @pageStart int=2,
    @pageEnd int=4,
    @result varchar(MAX),
    @numbers int output
as
   select @numbers = COUNT(*)  
   from products 
   where productName like @productName 

   select *
   from (select 
            *,
            ROW_NUMBER() over (order by ID) as row 
         from products 
         where productName like @productName) a 
   where a.row between @pageStart and @pageEnd

nameParam.Value它始终返回空值

当我在SQL Server Mgmt Studio中执行存储过程时,它似乎有一个值,但在c#中它始终为null

1 个答案:

答案 0 :(得分:3)

您必须枚举结果才能实际执行存储过程。试试这个:

public List<searchProducts_Result> GetProducts()
{
   var nameParam = new ObjectParameter("numbers", typeof(int));
   List<searchProducts_Result> listobjs = new List<searchProducts_Result>();

   // List<searchProducts_Result> objResult = null;

   searchProducts_Result outParam = new searchProducts_Result();
   using (var db = new SPWebEntities())
   {
      // by calling ToList() you execute the SP
      List<searchProducts_Result> objResult =
          db.searchProducts("asd", 2, 5, "15", nameParam).ToList();

      if (nameParam.Value != null)
         outParam.UserID = nameParam.Value.ToString();
      else
         outParam.UserID = "0";
      listobjs.Add(outParam);

      foreach (searchProducts_Result sr in objResult)
      {
         listobjs.Add(sr);
      }
   }

   return listobjs;
}