I can only output a database record. How do I output all the records I have in the database?

Asked

Viewed 33 times

-1

public ActionResult Index()
{
    PAPEntities db = new PAPEntities();
    MoviesData movie = db.MoviesData.SingleOrDefault(x => x.MovieID == 1);

    List<MovieViewModels> MovieVM = new List<MovieViewModels>
    {
        new MovieViewModels 
        {
            MovieID = movie.MovieID,
            MovieName = movie.MovieName,
            MovieDescription = movie.MovieDescription,
            MoviePrice = movie.MoviePrice,
            MovieCategory = movie.MovieCategory,
            MovieYear = movie.MovieYear
        }
    };

    return View(MovieVM);
}

View code

@foreach (var item in Model)
{
  <tr>
    <td>@item.MovieName</td>
    <td>@item.MovieCategory</td>
    <td>@item.MovieYear
    <td>@item.MoviePrice</td>
  </tr>
}
  • 3

    Damn, the code is specifying to get only one record!

  • Really? What do I have to change to get all the records?

  • 2

    When programming, search and understand what makes each line of your code

1 answer

2


The method SingleOrDefault serves precisely to obtain only one record according to the predicate passed by parameter.

You need to remove the call for this method.

MoviesData[] movies = db.MoviesData.ToArray();

The ToArray serves to perform the query in the bank and enumerate everything in memory. This could be postponed, but the method Select does not allow creating an instance of a class that is not an EF model - in the case of LINQ To Entities, to make it clear.

And then do the mapping for each item

movies.Select(m => new MovieViewModels
{
    MovieID = movie.MovieID,
    MovieName = movie.MovieName,
    MovieDescription = movie.MovieDescription,
    MoviePrice = movie.MoviePrice,
    MovieCategory = movie.MovieCategory,
    MovieYear = movie.MovieYear        
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.