Reputation: 1150
I've been playing around with the entity framework in MVC, but I seem to have run into a problem regarding 'lazy loading'. I have a simple web application that scrapes data from a well known movie database, and allows the user to save this data into a database. I have a Film class which contains details like title, release date, director.... etc. I also have a Genre class, and I have a icollection of genre inside the Film class.
The problem I am having is that I can't seem to load the genre information when I want to pass an IEnumerable query to a view.
Here is Film class:
public class Film
{
[Key]
public int FilmId { get; set; }
public string FilmTitle { get; set; }
public int FilmReleaseYear { get; set; }
public string FilmDirector { get; set; }
public string FilmRating { get; set; }
public string FilmImageUrl { get; set; }
public string FilmImdbUrl { get; set; }
public virtual ICollection<Genre> FilmGenres { get; set; }
public virtual ICollection<FilmCastMember> FilmCastList { get; set; }
public virtual ICollection<FilmReview> FilmReviews { get; set; }
public Film()
{
FilmGenres = new List<Genre>();
FilmCastList = new List<FilmCastMember>();
FilmReviews = new List<FilmReview>();
}
}
Here is my Genre class:
public class Genre
{
[Key]
public int GenreId { get; set; }
public string GenreType { get; set; }
}
Here is my action method
public ActionResult MyFilms()
{
IEnumerable<Film> films = from film in db.Films.Include("Genres")
select film;
return View(films);
}
The problem I have is that when i'm in the view for this method, I try to access the GenreType of a film using a foreach loop, however, it doesn't give me that option. All the data is linked inside my database, so i'm not sure what i'm doing wrong. Any help would be great.
New action method:
public ActionResult MyFilms()
{
IEnumerable<Film> films = from film in db.Films.Include("FilmReviews").Include("FilmGenres").Include("FilmCastList")
select film;
return View(films);
}
New View for that method:
@model IEnumerable<MvcFilmFinder.Models.Film>
@{
ViewBag.Title = "MyFilms";
}
@foreach (var film in Model)
{
<h2>@film.FilmTitle</h2>
<img src="@film.FilmImageUrl" alt="@film.FilmTitle" />
foreach (var genre in film.FilmGenres)
{
<p>@genre.GenreType</p>
}
foreach (var genre in film.FilmGenres)
{
<p>@genre.GenreId</p>
}
foreach (var review in film.FilmReviews)
{
<p>@review.ReviewAuthor</p>
}
}
Upvotes: 1
Views: 523
Reputation: 959
Change your Controller code to:
public ActionResult MyFilms()
{
var films = from film in db.Films.Include("FilmGenres")
select film;
return View(films);
}
Your view should look like this:
@model IEnumerable<projectname.Models.Film>
@foreach (var film in Model)
{
foreach (var genre in film)
{
// genre stuff
}
}
Upvotes: 1