EF核心+宇宙Db-一些构造函数参数映射,但不是其他没有



我在Cosmos Db中有以下类和数据。当从数据存储中检索数据时,一些属性不存在于存储的数据中,EF将它们映射为null(例如MiddleName(,但是DateOfBirthPhysicalAddress参数抛出"0";可为null的对象必须有一个值"错误我不明白为什么用户参数的处理方式不同。如果数据存储中未定义/不可用,我希望将任何丢失的属性设置为null。

public class User
{
private User(UserId userId, IdpId idpId, string firstName, string middleName, string lastName, string suffix,
string email, string phoneNumber, DateOnly dateOfBirth)
{
UserId = userId;
IdpId = idpId;
FirstName = firstName;
MiddleName = middleName;
LastName = lastName;
Suffix = suffix;
Email = email;
PhoneNumber = phoneNumber;
DateOfBirth = dateOfBirth;
}
public UserId UserId { get; } = UserId.New();
public IdpId IdpId { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Suffix { get; set; }
public string Email { get; set; }
public Address PhysicalAddress { get; set; }
public string PhoneNumber { get; set; }
public DateOnly DateOfBirth { get; set; }
public string ETag { get; set; }
}
public class Address
{
public string StreetLine1 { get; init; }
public string StreetLine2 { get; init; }
public string City { get; init; }
public string State { get; init; }
public static string Country => "US";
public string PostalCode { get; init; }
}

存储在Cosmos数据库中的项目

{
"UserId": "C8282366-A13C-48DF-9893-A5400DD73264",
"Created": "2021-06-27T12:09:54.556736-04:00",
"CreatedBy": "C8282366-A13C-48DF-9893-A5400DD73264@clients",
"Discriminator": "User",
"Email": "bob@bob.com",
"FirstName": "Bob",
"IdpId": "google-oauth2|111111111111111111111",
"LastModified": "2021-06-28T22:16:39.068558-04:00",
"LastModifiedBy": "C8282366-A13C-48DF-9893-A5400DD73264@clients",
"LastName": "King",
"id": "User|C8282366-A13C-48DF-9893-A5400DD73264"
}

调用以检索所有用户

var userList = await _dbContext.Users.ToListAsync(cancellationToken);

对于任何可能遇到此问题的人。DateOnly属性需要在构造函数和记录类中标记为可为null。Address属性不能用于构造函数绑定。请参阅:带有构造函数的实体类型

最终记录类别:

public record User
{
private User(UserId userId, IdpId idpId, string firstName, string middleName, string lastName, string suffix,
string email, string phoneNumber, DateOnly? dateOfBirth)
{
UserId = userId;
IdpId = idpId;
FirstName = firstName;
MiddleName = middleName;
LastName = lastName;
Suffix = suffix;
Email = email;
PhoneNumber = phoneNumber;
DateOfBirth = dateOfBirth;
}
public UserId UserId { get; } = UserId.New();
public IdpId IdpId { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Suffix { get; set; }
public string Email { get; set; }
public Address PhysicalAddress { get; set; }
public string PhoneNumber { get; set; }
public DateOnly? DateOfBirth { get; set; } 
public string ETag { get; set; }
}

最新更新