[英]MongoDB C#/.NET Driver - How to deserialize UUID and ISODate
我在 MongoDB 集合中有一个文档,如下所示:
{
_id: new UUID("31daac77-bcbc-4cd5-bb93-382440f46f16"),
CompanyId: 'XYZ',
RequestDate: ISODate("2023-01-10T07:52:32.840Z")
}
它对应于 object,如下所示:
public class ReportRequest
{
public ReportRequest(string companyId)
{
this.Id = Guid.NewGuid();
this.CompanyId = companyId;
this.RequestDate = DateTime.UtcNow;
}
[BsonId]
[BsonElement("_id")]
[BsonGuidRepresentation(GuidRepresentation.Standard)]
public Guid Id { get; }
[BsonElement]
public string CompanyId { get; }
[BsonElement]
[BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
public DateTime RequestDate { get; }
}
然后我尝试查询具有特定CompanyId
的所有文档:
public async Task PrintAvailableReportDatesAsync(string companyId)
{
var filter = Builders<ReportRequest>.Filter.Eq(r => r.CompanyId, companyId);
var cursor = await _collection.FindAsync(filter);
var reportRequests = await cursor.ToListAsync();
foreach (var req in reportRequests)
Console.WriteLine($"Id: {req.Id.ToString()}, Date: {req.RequestDate}");
}
我希望得到以下 output:
编号:31daac77-bcbc-4cd5-bb93-382440f46f16,日期:2023-01-10T07:52:32.840Z
相反,我得到这个:
编号:00000000-0000-0000-0000-000000000000,日期:0001-01-01T00:00:00
我究竟做错了什么?
根据我在本地进行的测试,这些属性的值是在构造函数中分配的。
有两种方法可以修复它:
方法 1:为所有属性提供设置器
public class ReportRequest
{
public ReportRequest(string companyId)
{
this.Id = Guid.NewGuid();
this.CompanyId = companyId;
this.RequestDate = DateTime.UtcNow;
}
[BsonId]
[BsonGuidRepresentation(GuidRepresentation.Standard)]
public Guid Id { get; set; }
public string CompanyId { get; set; }
[BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
public DateTime RequestDate { get; set; }
}
演示
方法 2:创建具有三个参数的构造函数
public class ReportRequest
{
...
public ReportRequest(Guid id, string companyId, DateTime requestDate)
{
this.Id = id;
this.CompanyId = companyId;
this.RequestDate = requestDate;
}
...
}
演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.