I created a service that retrieves users from the database with a one-to-one relationship and so I have this ApplicationUser
class
public class ApplicationUser
{
public required int Id { get; set; }
public required string Username { get; set; }
public required string ProfilePicture { get; set; }
public DateTime Created { get; set; } = DateTime.Now;
public UserProfile? Profile { get; set; }
}
And this is the service function
public async Task<ApplicationUser?> GetByUserIdAsync(int userId, bool includeProfile = false)
{
IQueryable<ApplicationUser> query = _dbContext.Users;
if (includeProfile)
{
query.Include(u => u.Profile);
}
return await query.FirstOrDefaultAsync(u => u.Id == userId);
}
As you can see I added a argument includeProfile
so that when I also need the user profile I can tell the function to include it.
The issue lies in the return type. Since ApplicationUser.Profile
is nullable, when I access that property in my code even if I pass true
for includeProfile
, I get the warning that Profile
could be null.
So my question is: How do I make it so that when includeProfile
is true, ApplicationUser.Profile
is not null?