I’m new to MVC.
In the tutorials I’ve gone through they say it is good practise to have your entities object disposed of after it is passed to the view. Like so…
using(MyProjectEntities db = new MyProjectEntities)
{
return View(db.PersonAddresses.ToList());
}
However I don’t want to just display the IDs of the Person and the Address records that are linked in the PersonAddress table. I want the whole shebang and I get an error when I do the following in my view.
<% foreach (var item in Model) { %>
<tr>
<td>
<%: item.Person.LastName + ", " + item.Person.FirstName %>
</td>
<td>
<%: item.Address.AddressLine1+ "<br />" + item.Address.AddressLine2 %>
</td>
<td>
<%: item.Room.RoomName %>
</td>
<td>
<%: String.Format("{0:g}", item.Date) %>
</td>
</tr>
<% } %>
However if do
MyProjectEntities db = new MyProjectEntities;
return View(db.PersonAddresses.ToList());
My view works fine.
Is there a better way of passing those values to the view where I can dispose of the Entities object properly?
One way is to “eager” load the data by adding .Include in your LINQ query, this pre-loads the specified data so it is ready to go.