I have a User
class with an owned entity PersonalInformation
that contains properties like FirstName
, LastName
, PhoneNumber
, etc.
The User
class is a table who's Id
is pulled from another login database AspNetUsers
that holds all login information.
When I try and read from the database, the PersonalInformation
object is always null
, even though data exists in the database. Here's the classes
public class User
{
public string Id { get; set; }
public PersonalInformation PersonalInformation { get; set; }
}
public class PersonalInformation
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string MobilePhone { get; set; }
public string HomePhone { get; set; }
public string WorkPhone { get; set; }
public string OtherPhone { get; set; }
public DateTime DateOfBirth { get; set; }
}
And here's the configuration
public class UserConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.HasKey(x => x.Id);
builder.OwnsOne(x => x.PersonalInformation, pi =>
{
pi.Property(x => x.FirstName).HasMaxLength(25);
pi.Property(x => x.MiddleName).HasMaxLength(25);
pi.Property(x => x.LastName).HasMaxLength(25);
pi.Property(x => x.MobilePhone).HasMaxLength(15);
pi.Property(x => x.HomePhone).HasMaxLength(15);
pi.Property(x => x.OtherPhone).HasMaxLength(15);
pi.Property(x => x.WorkPhone).HasMaxLength(15);
});
builder.Property(x => x.CreatedBy).HasMaxLength(36);
builder.Property(x => x.LastModifiedBy).HasMaxLength(36);
}
}
Here's an image of the database table we're pulling from
This is the call to the user table
var user = await context.Users
.FindAsync(_currentUserService.UserId);
I've also tried this one too
var user = await context.Users
.Include(x => x.PersonalInformation)
.FirstOrDefaultAsync(x => x.Id == _currentUserService.UserId);
When I examine user in the debugger, I see that User.PersonalInformation
is null
, even though there's data in the database.
I've looked on here for someone with a similar problem, and they suggested the following. Each did not fix my issue:
- Add
WithOwner()
toUserConfiguration
class - Add
virtual
toPersonalInformation
onUser
class (as if it was a navigation property) - Add
Include
+FirstOrDefaultAsync()
to query (as if it was a navigation property) - Upgrade to latest version of EF Core (3.1.6 as of this post)
I faced with the same problem and fixed it with explicit include of related object (used eager loading) https://learn.microsoft.com/en-us/ef/core/querying/related-data/