'Entity Framework Core v6.0.5 foreign key properties returning unexpected null
I read a LoginUser (an extension of IdentityUser) from the AspNetUsers table with Entity Framework Core v6.0.5.
When I attempt to read its foreign key property Company, the property is always null - why?
i.e.
var user = dbContext.Users
.FirstOrDefault(...);// A non-null LoginUser is returned
var companyId = user.CompanyId; // results in Integer 1 - as expected
var company = user.Company; // company is always null
Table definitions:
public class LoginUser : IdentityUser
{
public int CompanyId { get; set; } = -1;
public virtual Company Company { get; set; }
}
public class Company
{
public int Id { get; set; } = 0;
public virtual ICollection<LoginUser> LoginUsers { get; set; }
[Required]
[MaxLength(128)]
public string TradingName { get; set; } = string.Empty;
}
A foreign key index exists on the LoginUser table generated for the column CompanyId.
Any ideas what I have omitted to do?
AspNetUsers table data:
Id CompanyId Other User fields not shown...
8c568150-ecf8-46f4-8ec1-db9a7a66daaa 1
Companies table data:
Id TradingName
-----------------------
-1 Unassigned Company
1 Discovery
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
