【问题标题】:EF Core 3.1 Owned Entities returning null objects when querying databaseEF Core 3.1 拥有的实体在查询数据库时返回空对象
【发布时间】:2020-11-19 12:56:02
【问题描述】:

我有一个 User 类,其拥有的实体 PersonalInformation 包含 FirstNameLastNamePhoneNumber 等属性。

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.PersonalInformationnull,即使数据库中有数据。

我在这里寻找有类似问题的人,他们提出了以下建议。每个都没有解决我的问题:

  1. WithOwner() 添加到UserConfiguration
  2. User 类上将virtual 添加到PersonalInformation(就好像它是一个导航属性一样)
  3. 添加Include + FirstOrDefaultAsync() 进行查询(就好像它是一个导航属性)
  4. 升级到最新版本的 EF Core(截至本文为 3.1.6)

【问题讨论】:

    标签: c# entity-framework ef-core-3.1 owned-types


    【解决方案1】:

    我发现了问题。 DateTime DateOfBirth 在数据库中为空,导致整个对象为空。一旦我在数据库中提供了一个值,它就会按预期工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-27
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 2021-01-20
      • 2022-01-13
      相关资源
      最近更新 更多