[英]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.