[英]EF Core 3.1 Owned Entities returning null objects when querying database
我有一個User
class ,其擁有的實體PersonalInformation
包含FirstName
、 LastName
、 PhoneNumber
等屬性。
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.PersonalInformation
是null
,即使數據庫中有數據。
我在這里尋找有類似問題的人,他們提出了以下建議。 每個都沒有解決我的問題:
WithOwner()
添加到UserConfiguration
classUser
class 上將virtual
添加到PersonalInformation
(就好像它是導航屬性一樣)Include
+ FirstOrDefaultAsync()
進行查詢(就好像它是一個導航屬性)我發現了這個問題。 數據庫中的DateTime DateOfBirth
為 null,這導致整個 object 為 null。 一旦我在數據庫中提供了一個值,它就會按預期工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.