Reputation: 14159
Here is the code from my View:
@model IEnumerable<Sample2.Models.Leave_GetDetails_Result1>
@{
ViewBag.Title = "Index";
}
<div>
@foreach (var item in Model) {
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.LA_StaffCode)
</dt>
<dd>
@Html.DisplayFor(model => item.LA_StaffCode)
</dd>
<dd>
@Html.DisplayFor(model => item.LA_AppNo)
</dd>
</dl>
}
</div>
<p>
@*@Html.ActionLink("Edit", "Edit", new { id = Model.Staff_Code }) |*@
@Html.ActionLink("Back to List", "Index")
</p>
When I execute, it gives error:
"Calling 'Read' when datareader is closed is not a valid operation"
Edited:
The Controller code is below where I am calling a stored procedure:
using (var context = new Admin_TestEntities())
{
var data = context.Leave_GetDetails("Recommended");
return View(data.AsEnumerable());
}
Upvotes: 0
Views: 2335
Reputation: 24901
You need to call a method like ToList
in you data access layer to force the request to a database:
using (var context = new Admin_TestEntities())
{
var data = context.Leave_GetDetails("Recommended").ToList();
return View(data);
}
Methods like AsEnumerable()
do not make a request to a database. The request is only made when you first access the data (in your case - in a view) or when you explicitly call a method which makes a call to the database (for example ToList()
).
You get an error because when you try to access object in your view this is when the call to the database is actually made, but at the same time your object context
is already disposed. To fix it you should explicitly force database query using ToList
while the context is not yet disposed, that is in your controller method
Upvotes: 2