0

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.

1 Answer 1

1

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;

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that was the issue. I hate when I miss dumb things like this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.