Tuesday, February 16, 2016

Calling Stored Procedures from MVC

Earlier we had discussed on how to use database first approach in MVC 5.
Now I explored and way to use stored proc using database first approach

Ideally have a stored Proc Built in your SQL server


create procedure GetFunctions

As

Begin
       select FunctionId,FunctionName from   tblFunction
End

Now in the Visual Studio we add a new model . we add a edmx file as below
 
 
we now create a new SQL connection
 
Now we will choose a the stored proc we created
you can go to model browser and edit the properties as below
 
GetFunction above is the one which I have defined to call the stored procedure from MVC 
 
Now create controller
public class FuncController : Controller
 
 
 
 
{
 
//
// GET: /Func/
testdbEntities4 db = new testdbEntities4();
public ActionResult Index()
 
 
{
 
return View(db.GetFunctions());
 
 
}
}
 
Create Views
@model IEnumerable<RiskPOC.Models.Functions>



@{
 
ViewBag.Title = "Index";



}
 
<h2>Index</h2>

<table>

<tr>

<th>



@Html.DisplayNameFor(model => model.First().FunctionName)
 
</th>

</tr>

@foreach (var item in Model)



{
 
<tr>

<td>



@Html.DisplayFor(model=>item.FunctionName)
 
</td>

</tr>



}
 
</table>
 
And finally run the solution 
 
Compare it with Database