MongoDB C#/.NET驱动程序-如何反序列化UUID和ISODate

oaxa6hgo  于 2023-01-12  发布在  Go
关注(0)|答案(1)|浏览(99)

我在MongoDB集合中有一个文档,如下所示:

{
  _id: new UUID("31daac77-bcbc-4cd5-bb93-382440f46f16"),
  CompanyId: 'XYZ',
  RequestDate: ISODate("2023-01-10T07:52:32.840Z")
}

它对应的对象如下:

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}");
}

我希望得到以下输出:
编号:31 daac 77-bcbc-4cd 5-bb 93 - 382440 f46 f16,日期:2023年1月10日零时07分52秒32.840秒
结果,我得到了这个:
编号:00000000-0000 - 0000 - 0000- 0000,日期:00时01分01秒01秒00时00分
我哪里做错了?

lp0sw83n

lp0sw83n1#

从我在本地端的测试来看,这些属性的值是在构造函数中赋值的。
有两种方法可以解决这个问题:

    • 方法1:为所有属性提供setter**
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; }
}

演示

    • 方法二:创建具有三个参数的构造函数**
public class ReportRequest
{
    ...

    public ReportRequest(Guid id, string companyId, DateTime requestDate)
    {
        this.Id = id;
        this.CompanyId = companyId;
        this.RequestDate = requestDate;
    }

    ...
}

演示

相关问题