I hope this isn't a duplicate as I have been looking but I was looking more at the reasoning behind this.
I have set up a user object.
public class User
{
public User()
{
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserID { get; set; }
public Guid UserGuid { get; set; }
public string Email { get; set; }
public string Name { get; set; }
public int CompanyID { get; set; }
public int StatusID { get; set; }
[ForeignKey("StatusID")]
public Status Status { get; set; }
public int RoleID { get; set; }
[ForeignKey("RoleID")]
public UserRole UserRole { get; set; }
}
And the Child Objects
public class UserRole
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int RoleId { get; set; }
public string Role { get; set; }
}
public class Status
{
[Key]
public int StatusId { get; set; }
public string Description { get; set; }
}
When I call
var testuser = dbContext.User.Where(u => u.CompanyID == 1).FirstOrDefault();
I get users.Status as being null, but users.StatusID = 1.
however, if I call
var status = dbContext.Status.ToList();
var role = dbContext.UserRole.ToList();
var testuser = dbContext.User.Where(u => u.CompanyID == 1).FirstOrDefault();
then call testuser.Status, I can see the correct object related to StatusId of 1.
Can someone explain why this would solve the issue and also how I can make it work without having to call the following beforehand.
var status = dbContext.Status.ToList();
Thanks