I am walking through a sample MVC4 ASP.NET tutorial available on PluralSight.com, by Scott Allen. I am in a section #5, Working with Data (part 2), "Listing Reviews".
This application has a database of restaurant reviews. I'm following a section right now in which Scott shows how to add links in the Restaurant view that will display a list of reviews for the selected restaurant.
There was a problem when clicking the link to display the reviews, encountered in the following cshtml file. The problem was that Model.Reviews
in the parameters for Html.Partial
method was null
by default.
Index.cshtml
@model OdeToFood.Models.Restaurant
@{
ViewBag.Title = "Index";
}
<h2>Reviews for @Model.Name</h2>
@Html.Partial("_reviews", Model.Reviews)
<p>
@Html.ActionLink("Create New", "Create")
</p>
Scott explained that the Model class Restaurant
, listed below, will load all the properties except for Reviews, which are stored in another table somewhere else. He said there are many ways to fix the problem, but the easiest way to make EF load the reviews is to make the Reviews
property virtual
.
Model class Restaurant
public class Restaurant
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public ICollection<RestaurantReview> Reviews { get; set; }
}
He said that at run time, the EF creates a "wrapper" for the restaurant class that will intercept calls (I don't understand this) to the Reviews
property so that when you get to the reviews in the view, The EF will load them up instead of being null
.
My concern is that making a property virtual
when you don't intend to override it, is bad coding practice. If so, what is the best coding practice here? I'm also wondering if the simplest solution is the best solution here.
making a property virtual when you don't intend to override it, is bad coding practice
-- but it is being overridden by generated code. \$\endgroup\$