Search code examples
asp.net-mvc3-tier

Object reference not set to an instance of an object MVC 5


I'm new to MVC working on 3-tier MVC project and i am using a ready database.

now i need to write a query using linq in Business Layer to bring list of doctors like this :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DoctorsSheet.DataAccess;

namespace DoctorsSheet.Business
{
    class Doctor : IDoctor
    {
        DoctorsSheetDBEntities db = new DoctorsSheetDBEntities();

        public IQueryable<Doctors> GetDoctors()
        {
            var doctors = from d in db.Doctors
                          select d;

            return doctors.AsQueryable<Doctors>();
        }
     }
}

and when i call GetDoctors() from DoctorsController it tell me Object reference not set to an instance of an object

this is the Controller :

public ActionResult Index()
{
    var doctors = obj.GetDoctors().AsQueryable<Doctors>();
    return View(doctors);
}

please help me how to fix it.


Solution

  • Make your class public -

    public class Doctor : IDoctor
    

    And then initiate obj variable as shown below and then use obj.

    IDoctor obj = new Doctor();
    

    NOTE: As @Sippy explained there is no need for you to use GetDoctors().AsQueryable<Doctors>();.