6

I am new to MVC, and trying to call a stored proc from the controller.

In the model I have edmx which has all stored procs as functions

Cannot implicitly convert type System.Collections.Generic.IEnumerable<MVC.Models.xxcomplextype_result> to System.Web.Mvc.ActionResult
An explicit conversion exists.

I created an object for the entity in the controller and in an action result function I called the function calling the stored proc and it returned the above error. How should I convert the result set to actionresult?

Code Sample

public class DBController : Controller
{
    XXXXXXXEntities xXXXXXEntities = new XXXXXXXEntities();

    public IEnumerable<usp_xxxxx_Result> usp_xxxxx()
    {
        return XXXXXEntities.usp_xxxxx();
    }
}

public ActionResult ViewQuery() {
    DBController dBController = new DBController();

    return dBController.usp_xxxxx();
}
tereško
  • 58,060
  • 25
  • 98
  • 150
Vignesh Subramanian
  • 7,161
  • 14
  • 87
  • 150

2 Answers2

9

You'll need to return a class that inherits from ActionResult.

Probably you want something like:

public ActionResult ViewQuery() {
        DBController dBController = new DBController();
        return View(dBController.usp_xxxxx());
}

This returns the view with the result passed in as Model.

If you want to return JSON use:

public ActionResult ViewQuery() {
        DBController dBController = new DBController();
        return JSON(dBController.usp_xxxxx());
}
Gideon
  • 18,251
  • 5
  • 45
  • 64
  • worked like a charm :D btw is this the right way to call stored procs in mvc? Sorry i am new to it – Vignesh Subramanian Dec 23 '13 at 07:10
  • In general that's ok. Although keep in mind that your UI is now super-bound to the structure of the stored procedure. So that if you change a property in your sp, your UI layer also has to change. A workaround is to return a "ViewModel", which is a class that is "specific" to the view, and not to the DB. You'll convert your stored procedure class to the "ViewQueryVM" class, and return that one. – Gideon Dec 23 '13 at 07:13
1

.ToArray() solves the issue.

public class DBController : Controller
{
    XXXXXXXEntities xXXXXXEntities = new XXXXXXXEntities();

    public IEnumerable<usp_xxxxx_Result> usp_xxxxx()
    {
        return XXXXXEntities.usp_xxxxx();
    }
}

public ActionResult ViewQuery() {
    DBController dBController = new DBController();

    return dBController.usp_xxxxx().ToArray();
}
Tomas Kubes
  • 23,880
  • 18
  • 111
  • 148