0

I am trying to make login authentication for 3 types of roles, log in as a admin or a students its work but when i logged in as teacher its give error"System.NullReferenceException: 'Object reference not set to an instance of an object.'"
please review the code and give me the some good solution....

 public bool LoggingIn(ref bool logged, out bool startup)
    {
        string pswd;
        Console.Write("Write your Email :");
        email = Console.ReadLine();
        Console.Write("Write your Password :");
        pswd =Console.ReadLine();

        var adminContext = new UMSDbContext();
        var tchremail = (adminContext.Teachers.Where(t => t.Email == email).FirstOrDefault());
        var stdemail = (adminContext.Students.Where(s => s.Email == email).FirstOrDefault());
        var data = (adminContext.Admins.Where(u =>u.Email == email && u.Password==pswd).FirstOrDefault());
        if (data != null && email == "rana@gmail.com")
        {
            Console.WriteLine("Login Succesully");
            Console.WriteLine();
            logged = true;
            startup = false;
            RunAdmin();
            return logged;
        }
        else if (data != null && email == stdemail.Email)
        {
            Console.WriteLine("Login Succesully");
            Console.WriteLine();
            logged = true;
            startup = false;
            RunStudent();
            return logged;
        }
        else if (data != null && email == tchremail.Email)
        {
            Console.WriteLine("Login Succesully");
            Console.WriteLine();
            logged = true;
            startup = false;
            RunTeacher();
            return logged;
        }
        else
        {
            Console.WriteLine(" Invalid Email or Password");
            Console.WriteLine();
            startup = true;
            return logged;
        }
    }
  • `.FirstOrDefault()` can return null, and you are not checking for null in all the variables. For example `stdemail.Email` could raise a `NullReferenceException` – Cleptus Jun 27 '19 at 07:13
  • I am usually against indiscriminate usage of `.FirstOrDefault()` in this use case `SingleOrDefault()` or `Single()` make more sense when looking for emails. It depends on what data do you work with ofcourse. – Cleptus Jun 27 '19 at 07:16
  • @mjwills var stdemail = (adminContext.Students.Where(s => s.Email == email).FirstOrDefault() line was creating issue cause of finding null if teacher login so it was solved by add check in both " stdemail != null " – Rao Saqib Jun 28 '19 at 11:35
  • @bradbury9 thanks dear thats was the problem and solved by check as above in both line teacher n student – Rao Saqib Jun 28 '19 at 11:37

0 Answers0