0

I am getting a run time error of "Object reference not set to an instance of an object." for posts in the following code, would anyone be able to help me fix?

private HomeIndexModel BuildHomeIndexModel()
        {
            var LatestPosts = _postService.GetLatestPosts(10);

            var posts = LatestPosts.Select(post => new PostListingModel
            {
                Id = post.Id,
                Title = post.Title,
                AuthorId = post.User.Id,
                AuthorName = post.User.UserName,
                AuthorRating = post.User.Rating,
                DatePosted = post.Created,
                RepliesCount = post.Replies.Count(),
                Forum = GetForumListingForPost(post)
            });

            return new HomeIndexModel()
            {
                LatestPosts = posts
            };
        }

GetLatestPosts() from the post service is as follows

public IEnumerable<Post> GetLatestPosts(int count)
        {
            var allPosts = GetAll().OrderByDescending(post => post.Created);
            return allPosts.Take(count);
        }
Vergil
  • 9
  • 2
  • Yes, and no. I understand what is happening in the broad sense, but I don't know how to fix it. var posts is the object throwing a null reference, but as far as I can tell, I have initialised it, so I don't understand why I am getting the error. – Vergil Apr 29 '22 at 03:52
  • posts throwing it is probably a red-herring because it is an innumerable. Without seeing more of the error. I suggest you walk through each creations of PostListingModel and check which of the propert properties on the post object and make sure they are not null. Or just update the code to expect things to be null i.e. us null propogation with a default value. e.g. post?.User.UserName ?? "doesn't exist". Also you can add a ToList() after the select to force the error earlier. – Heinrich Apr 29 '22 at 04:03

0 Answers0