Search code examples
asp.net-mvcasp.net-identitycode-first

Html.DisplayFor query through other table returning an empty string


I have hit a roadblock when attempting to figure out how to make user profiles using ASP.Net Identity. I have my database set up like this, where Id in AspNetUsers a foreign key to the table UserPages.

I'm using standard code to deliver the model to the view:

public ActionResult View(string id)
{
    UserPage userPage = db.UserPages.Find(id);
    (...)
    return View(userPage);
}

My model:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.WebPages.Html;

namespace Citrus.Models
{
    public class UserPage
    {
        [Key]
        public string Id { get; set; }

        [ForeignKey("Id")]
        public ApplicationUser User { get; set; }

        public string AboutMe { get; set; }

        public string AvailableTime { get; set; }

    }
}

And then in the view I can use

@Html.DisplayFor(model => model.AboutMe)

to display the property AboutMe in the db UserPages. But when I try to fetch data from AspNetUsers through the model like so:

@Html.DisplayFor(model => model.User.Name)

I only get an empty string back. User.Name is non-nullable, and the entry exists in the database. What is the reason for the method to come back empty, and how can this be resolved?


Solution

  • Turns out that I never included AspNetUsers to the UserPages query.

    UserPage userPage = db.UserPages.Find(id);
    

    Replacing my query with the following code resolves the problem:

    UserPage userPage = db.UserPages.Include(x => x.User).Where(x => x.Id == id).FirstOrDefault()
    

    I can now get any property of the user by using @Html.DisplayFor(model => model.User.Property)