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

.net-core .net-core-2.0 asp.net-core-identity c# entity-framework-core


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; }

    public virtual City UserCity { get; set; }

    public virtual Organization Organization { get; set; }

    public int? OrganizationId { get; set; }

    public bool AddToConstantContact { get; set; }
1/22/2019 1:26:33 PM

Accepted Answer

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)

For Your code Will be something like


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://docs.microsoft.com/en-us/ef/core/querying/related-data

5/14/2018 2:48:11 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow