c# MVC "object reference not set to an instance of an object" Yet the UserId has a value

I've got a null reference error. My code is below, the error points to the 'return user.Applications.ToList();' of GetApplications method. Any tips how to fix it would be greatly appreciated.

UserDAO:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NAA.Data.IDAO;
using NAA.Data.Models.Domain;
using NAA.Data.Repository;


namespace NAA.Data.DAO
{
    public class UserDAO : IUserDAO
    {

        public User GetUser(string Userid, NAAContext context)
        {
            return context.Users.Find(Userid);
        }
        public void AddUniversityToCollection(Application application, University university, NAAContext context)
        {
            context.Universities.Find(university.UniversityId).Applications.Add(application);
        }


        public void AddUser(User user, NAAContext context)
        {
            context.Users.Add(user);
            context.SaveChanges();

        }
        public IList<Application> GetApplications(string UserId, NAAContext context)
        {
            context.Users.Include(g => g.Applications).ToList();
            User user = context.Users.Find(UserId);
            return user.Applications.ToList();
        }

        public void AddUniversityToCollection(Application newApplication, User user, NAAContext context)
        {
            context.Applications.Find(newApplication.ApplicationId);
        }
    }
}

IUserDAO: I doubt the problem is here

using NAA.Data.Models.Domain;
using NAA.Data.Repository;
using NAA.Data.DAO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NAA.Data.IDAO
    
{
    public interface IUserDAO
    {
        void AddUser(User user, NAAContext context);
        User GetUser(string userID, NAAContext context);
        void AddUniversityToCollection(Application newApplication, User user, NAAContext context);
        IList<Application> GetApplications(string UserId, NAAContext context);
    }
}

UserService:

using NAA.Data.Models.Domain;
using NAA.Data.Repository;
using NAA.services.IService;
using NAA.services.Models;
using NAA.Data.DAO;
using NAA.Data.IDAO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NAA.services.Service
{
    public class UserService : IUserService
    {
        private IUserDAO userDAO;
        public UserService()
        {
            userDAO = new UserDAO();
        }
        public void AddUser(User newUser)
        {
         
       using (var context = new NAAContext())
            {
                userDAO.AddUser(newUser, context);
            }
        }



        public User GetUser(string userId)
        {
            using (NAAContext context = new NAAContext())
            {
                return context.Users.Find(userId);
            }
       
            }
        public IList<Application>GetApplications(string UserId)
        {
            using (var context = new NAAContext())
            {
                return userDAO.GetApplications(UserId, context);
            }
        }
            }


                
        }

IUserService:

using NAA.Data.Models.Domain;
using NAA.Data.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NAA.services.IService;
using NAA.services.Service;
using NAA.services.Models;

namespace NAA.services.IService
{
    public interface IUserService
    {
        User GetUser(string userId);
        void AddUser(User newUser);
        IList<Application> GetApplications(string UserId);
    }

}

UserController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NAA.services.IService;
using NAA.services.Service;
using NAA.Data.Models.Domain;
using NAA.Data.Repository;
using NAA.services.Models;

namespace NAA.Controllers
{
    public class UserController : Controller
    {
        IUserService UserService;
        public UserController()
        {
            UserService = new UserService();
        }

        // GET: User
        public ActionResult AddUser() //string userId, string email (add later)
        {
            return View();
        }

           // POST: User/Create
           [HttpPost]
        public ActionResult AddUser(User newUser, NAAContext context)
        {
            try
            {
                // TODO: Add insert logic here
                UserService.AddUser(newUser);
                return RedirectToAction("GetUser", "User", new {id = newUser.UserId });
            }
            catch
            {
                return RedirectToAction("GetUser", "User", new { id = newUser.UserId });
            }
        }  
        public ActionResult GetUser(string id)
        {
            return View(UserService.GetUser(id));
        }

        public ActionResult GetApplications(string UserId)
            {
            return View(UserService.GetApplications(UserId));
            }
        // GET: User/Details/5
        // GET: User/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: User/Create
        [HttpPost]
   

        // GET: User/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: User/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: User/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: User/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

GetApplications view:

@model IEnumerable<NAA.Data.Models.Domain.Application>

@{
    ViewBag.Title = "GetApplications";
}

<h2>GetApplications</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Course)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Statement)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.TeacherContact)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.TeacherReference)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Firm)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Course)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Statement)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.TeacherContact)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.TeacherReference)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Firm)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ApplicationId }) |
            @Html.ActionLink("Details", "Details", new { id=item.ApplicationId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ApplicationId })
        </td>
    </tr>
}

</table>

Thank you in advance guys I'm really struggling with this and I can't work out how I'd fix it.

EDIT!

Application class:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NAA.Data.Models.Domain
{
   
    public class Application
    {
        [Key]
        public int ApplicationId { get; set; }
        public string Course { get; set; }
        public string Statement { get; set; }
        public string TeacherContact { get; set; }
        public string TeacherReference { get; set; }
        public char Offer { get; set; }
        public bool Firm { get; set; }
    }
}

User class:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NAA.Data.Models.Domain
{
    public class User
    {
        [Key]
        public string UserId { get; set; }
        public string Name { get; set; }
        
        public string Address { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public virtual ICollection<Application> Applications { get; set; }
        public virtual ICollection<University> Universities { get; set;}
    }
}

1 answer

  • answered 2021-02-20 16:24 Sergey

    Try to change your action:

    public IEnumerable<Application> GetApplications(string UserId, NAAContext context)
            {
                   var user =context.Users
                        .Include(a => a.Applications)
                         .Where (u=> u.UserId==UserId)
                          .FirstOrDefault();
                 
                return user.Applications;
             }