簡體   English   中英

EF Core 3.1 擁有的實體在查詢數據庫時返回 null 對象

[英]EF Core 3.1 Owned Entities returning null objects when querying database

我有一個User class ,其擁有的實體PersonalInformation包含FirstNameLastNamePhoneNumber等屬性。

User class 是一個表,其Id是從另一個包含所有登錄信息的登錄數據庫AspNetUsers中提取的。

當我嘗試從數據庫中讀取時, PersonalInformation object 始終是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);

    }
}

這是我們從中提取的數據庫表的圖像

這是對用戶表的調用

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 class
  2. User class 上將virtual添加到PersonalInformation (就好像它是導航屬性一樣)
  3. 添加Include + FirstOrDefaultAsync()進行查詢(就好像它是一個導航屬性)
  4. 升級到最新版本的 EF Core(截至本文為 3.1.6)

我發現了這個問題。 數據庫中的DateTime DateOfBirth為 null,這導致整個 object 為 null。 一旦我在數據庫中提供了一個值,它就會按預期工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM