1

Im a newbie and got this project from a friend that keeps telling me Error “Object reference not set to an instance of an object.” Could someone kindly help with this line 15

Line 13:         {
Line 14:            ViewBag.ResumeId = firstResume.ResumeId;
Line 15:            var firstResume = _context.Resumes.FirstOrDefault();
Line 16:             return View(firstResume);            
Line 17:         }
  • `_context.Resumes` is null. That much you could have gotten through the debugger. Now, *why* it's null, is another matter and can't be determine from the code you've provided. – Chris Pratt Aug 08 '14 at 21:29
  • 3
    Actually, I think your code paste is off somehow. You're calling `firstResume` before it's defined. Which should give you a compiler error long before you get the runtime error that brought you here. – Chris Pratt Aug 08 '14 at 21:32
  • Hi there, thanks for your reply. Heres the full code paste namespace LiveCV.Controllers { public class HomeController : Controller { LiveCV.Models.LiveCVContext _context = new Models.LiveCVContext(); public ActionResult Index() { var firstResume = _context.Resumes.FirstOrDefault(); ViewBag.ResumeId = firstResume.ResumeId; return View(firstResume); } public ActionResult About() { return View(); } } } – Habeeb Sulu Aug 10 '14 at 08:55
  • Hi there @ChrisPratt heres the full code http://pastebin.com/HsJc4jfj – Habeeb Sulu Aug 10 '14 at 09:00

1 Answers1

1

Well, I'm not sure if it's still line 15, but I would think that the error is actually originating from the line:

ViewBag.ResumeId = firstResume.ResumeId;

Most likely, firstResume is null since the result of FirstOrDefault will either be an instance or null. You need to need to always check that you actually got something back before trying to use it:

var firstResume = _context.Resumes.FirstOrDefault();
if (firstResume != null)
{
    ViewBag.ResumeId = firstResume.ResumeId;
}

However, if it's an object that your view can't live without, it's more typical to do something like:

if (firstResume == null)
{
    return new HttpNotFoundResult();
}

And then you can use the object as you please, since a 404 response would have already been returned if it was null.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444