MVC 4:带有/多个参数的存储过程

时间:2013-03-13 16:11:12

标签: asp.net-mvc json entity-framework stored-procedures tolist

使用Visual Studio Express 2012,MVC4 Web应用程序和SQL 2008 R2 ...

我曾经有一个只接受一个参数的存储过程,当我的MVC模型包含该存储过程时,我可以从我的Controller成功调用它并获得Json结果。< / p>

现在我已更新存储过程以接受两个参数。我刷新了我的MVC模型,但在传递两个参数时无法从我的控制器中正确调用存储过程。

这是我的旧存储过程和控制器使用一个参数(这有效):

PROCEDURE [dbo].[GetDependencyNodes]     
@CISearchString nvarchar(100)

旧控制器:

namespace CMDB.Controllers
{
public class GoJSDiagramNodesAndLinksController : Controller
{
   private CMDBEntities db = new CMDBEntities();
   public ActionResult GetDependencyNodes(string CISearchString)
    {
        return Json(db.GetDependencyNodes(CISearchString).ToList(), JsonRequestBehavior.AllowGet);
    }
}
}

这是我的新存储过程和控制器接受两个参数:

PROCEDURE [dbo].[GetDependencyNodes]
@CISearchString nvarchar(100),
@ExcludeString nvarchar(100)

新控制器:

namespace CMDB.Controllers
{
public class GoJSDiagramNodesAndLinksController : Controller
{
   private CMDBEntities db = new CMDBEntities();
   public ActionResult GetDependencyNodes(string CISearchString, string ExcludeString)
    {
   return Json(db.GetDependencyNodes(CISearchString, ExcludeString).ToList(), JsonRequestBehavior.AllowGet);
    }
}
}

在Visual Studio Express 2012中,我的“返回Json”行收到错误声明:

'int'不包含'ToList'的定义,并且找不到接受类型'int'的第一个参数的扩展方法'ToList'。

如果我改变了以下行:

return Json(db.GetDependencyNodes(CISearchString, ExcludeString).ToList(), JsonRequestBehavior.AllowGet);

为:

return Json(db.GetDependencyNodes(CISearchString, ExcludeString).ToString().ToList(), JsonRequestBehavior.AllowGet);

错误消失但控制器返回-1而不是正确的Json结果。我已经在SQL Manager中测试了存储过程,并且可以看到预期的结果。

以下是我的文件CMDBModels.Desginer.cs中包含GetDependencyNodes的部分代码:

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    /// <param name="cISearchString">No Metadata Documentation available.</param>
    /// <param name="excludeString">No Metadata Documentation available.</param>
    public int GetDependencyNodes(global::System.String cISearchString, global::System.String excludeString)
    {
        ObjectParameter cISearchStringParameter;
        if (cISearchString != null)
        {
            cISearchStringParameter = new ObjectParameter("CISearchString", cISearchString);
        }
        else
        {
            cISearchStringParameter = new ObjectParameter("CISearchString", typeof(global::System.String));
        }

        ObjectParameter excludeStringParameter;
        if (excludeString != null)
        {
            excludeStringParameter = new ObjectParameter("ExcludeString", excludeString);
        }
        else
        {
            excludeStringParameter = new ObjectParameter("ExcludeString", typeof(global::System.String));
        }

        return base.ExecuteFunction("GetDependencyNodes", cISearchStringParameter, excludeStringParameter);
    }

有什么想法吗?

感谢。

1 个答案:

答案 0 :(得分:1)

有些事情首先将您的数据访问移动到另一个类,让您的控制器尽可能轻。

接下来将存储的procure输出映射到具有与返回列匹配的属性的基本类(实体类)

这应该让你更容易看看调试中返回的数据,这只是一个很好的编程实践