I have a project and user Model that inherits the default identity class.
These two share a many to many relationship.
public class Project
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public ICollection<AppUser> users { get; set; }
}
public class AppUser : IdentityUser
{
public string DisplayName { get; set; }
public ICollection<Project> projects { get; set; }
}
In my projects controller I display all the projects that belong to the current user; (I check for the user with the user id)
[Authorize]
public IActionResult Index()
{
var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
IEnumerable<Project> objProjectList = _unitOfWork.Project.Where(userId);
return View(objProjectList);
}
and on the post method I'm trying to add the current user to the newly created project object to establish the relation between these two i.e. (this user is a member of this project) I've used dependency injection to inject usermanager that uses my custom user class (Appuser, which inherits the default scaffolded identity)
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public async Task<IActionResult> CreateAsync(Project obj)
{
if (ModelState.IsValid)
{
AppUser user = await _userManager.GetUserAsync(User);
obj.users.Add(user);
_unitOfWork.Project.Add(obj);
_unitOfWork.Project.Save();
return RedirectToAction("Index");
}
else
{
return View(obj);
}
}
However I'm getting the following error;
System.NullReferenceException: 'Object reference not set to an instance of an object.'
What exactly am I doing wrong? Should I be adding the user some other way?
I'd appreciate any input, thanks.
CodePudding user response:
In your model design:
public ICollection<AppUser> users { get; set; }
ICollection
is an interface, you can't use it to add something direcetly, Or you will get NullReferenceException
. You can create an instance, and then use it to add what you want.
AppUser user = await _userManager.GetUserAsync(User);
//create an instance.
List<AppUser> users = new List<AppUser>();
users.Add(user);
obj.users = users;
_unitOfWork.Project.Add(obj);
_unitOfWork.Project.Save();
return RedirectToAction("Index");