benmartin101
benmartin101

Reputation: 74

Entity Framework dbcontext crashing during foreach loop

I have an asp.net core mvc project. I'm trying to get over 300+ records from a table(s) using entity framework. Here are the models I have:

  public partial class Movies
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public virtual MovieInfoes MovieInfoes { get; set; }
    }

    public partial class MovieInfoes
    {
        public int Id { get; set; }
        public string Actors { get; set; }
        public string Director { get; set; }
        public virtual Movies IdNavigation { get; set; }
    }

In the controller section, I have an action that is suppose to list the title, actors, and director data.

 public IActionResult ListAllMovies()
    {
        var movies = context.Movies.Include("MovieInfoes").ToList();
        foreach (var movie in movies)
        {
            string x = movie.MovieInfoes.Actors;
        }
        return View(movies);
    }

For some reason, it is crashing after it iterates 19 records (I'm trying to iterate thru 300+ records). I get an error saying "NullReferenceException: Object reference not set to an instance of an object".

Note: I've tried with lazy loading and eager loading, and both ways result in same error.

Upvotes: 0

Views: 352

Answers (1)

Jesse Johnson
Jesse Johnson

Reputation: 1718

You're likely attempting to access movie.MovieInfoes.Actors with an instance of movie that has a null MovieInfoes reference.

Try accessing Actors with a null-conditional operator by changing string x = movie.MovieInfoes.Actors; to string x = movie?.MovieInfoes?.Actors;

Upvotes: 1

Related Questions