【发布时间】:2020-11-19 12:56:02
【问题描述】:
我有一个 User 类,其拥有的实体 PersonalInformation 包含 FirstName、LastName、PhoneNumber 等属性。
User 类是一个表,其 Id 是从另一个包含所有登录信息的登录数据库 AspNetUsers 中提取的。
当我尝试从数据库中读取数据时,PersonalInformation 对象始终为null,即使数据库中存在数据。这是课程
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; }
}
这是配置
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
这是对用户表的调用
var user = await context.Users
.FindAsync(_currentUserService.UserId);
这个我也试过了
var user = await context.Users
.Include(x => x.PersonalInformation)
.FirstOrDefaultAsync(x => x.Id == _currentUserService.UserId);
当我在调试器中检查用户时,我看到 User.PersonalInformation 是 null,即使数据库中有数据。
我在这里寻找有类似问题的人,他们提出了以下建议。每个都没有解决我的问题:
- 将
WithOwner()添加到UserConfiguration类 - 在
User类上将virtual添加到PersonalInformation(就好像它是一个导航属性一样) - 添加
Include+FirstOrDefaultAsync()进行查询(就好像它是一个导航属性) - 升级到最新版本的 EF Core(截至本文为 3.1.6)
【问题讨论】:
标签: c# entity-framework ef-core-3.1 owned-types