Search code examples
c#.net-coreentity-framework-coreasp.net-core-identity.net-core-2.0

.net core 2 Entity Framework - ApplicationUser Extended Foreign Key object not populating on get


I've extended the ApplicationUser to include a OrganizationId and a Organization object that is supposed to map to a foreign Organization table. This works fine on initial user registration - if it is an existing Organization, I just populate the OrganizationId field. If it is a new Organization, I instantiate a new Organization object and a new Organization gets created in the Organization table.

When I pull the record down with GetUserAsync, the correct CityId and OrganizationId fields are pulled. The UserCity and Organization objects are NULL though. I know I can do a manual lookup to query for a City/Organization based on the IDs returning, but I was wondering if Entity Framework has a mechanism to populate these two objects with the foreign keyed counterparts automatically on GetUserAsync.

var user = await _userManager.GetUserAsync(User);

public class ApplicationUser : IdentityUser
{
    public String FirstName { get; set; }

    public String LastName { get; set; }

    public int? CityId { get; set; }

    [ForeignKey("CityId")]
    public virtual City UserCity { get; set; }

    [ForeignKey("OrganizationId")]
    public virtual Organization Organization { get; set; }

    public int? OrganizationId { get; set; }

    public bool AddToConstantContact { get; set; }
}

Solution

  • While Fetching Records you need to use include keyword to get the referenced values. Ex

    using (var context = new BloggingContext())
    {
        var blogs = context.Blogs
        .Include(blog => blog.Posts)
        .ToList();
    }
    

    For Your code Will be something like

    context.Include("Organization").Include("City")
    

    Its also not loaded automatically in entity framework core because lazy loading is not supported yet till version 2.1.

    For more Info check https://learn.microsoft.com/en-us/ef/core/querying/related-data