The following classes are used to define an ApplicationUser with nested objects using composition, while also providing the view with a nested property.
When visiting ~/Views/Type1/Index.cshtml
, the following error is output:
NullReferenceException: Object reference not set to an instance of an object.
When looking at the property in the database, the Type1FK is set within the user's record, so I'm not sure why it is not accessible through the controller/view. How can a nested property be set and accessed correctly?
AppUser.cs
using Microsoft.AspNetCore.Identity;
namespace MyApp.Models
{
public class AppUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
[ForeignKey("Type1FK")]
public Type1 Type1 { get; set; }
}
}
Type1.cs
namespace MyApp.Models
{
public class Type1
{
public int Type1Id { get; set; }
public string Property1 { get; set; }
public AppUser AppUser { get; set; }
}
}
Type1Controller.cs
using System.Threading.Tasks;
using MyApp.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace MyApp.Controllers
{
[Authorize(Roles = "Type1")]
public class Type1Controller : Controller
{
private UserManager<AppUser> userManager;
public Type1Controller (UserManager<AppUser> _userManager)
{
userManager = _userManager;
}
[HttpGet]
public async Task<IActionResult> Index()
{
AppUser user = await userManager.GetUserAsync(HttpContext.User);
ViewBag.name = user.Type1.Name;
return View("~/Views/Type1/Index.cshtml");
}
}
}
~/Views/Type1/Index.cshtml
<div class="container-fluid">
<h1>@ViewBag.name</h1>
</div>