I have a document in a MongoDB collection like so:
{
_id: new UUID("31daac77-bcbc-4cd5-bb93-382440f46f16"),
CompanyId: 'XYZ',
RequestDate: ISODate("2023-01-10T07:52:32.840Z")
}
It corresponds to an object like so:
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; }
}
I then try to query for all documents with a particular 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}");
}
I would expect to get the following output:
Id: 31daac77-bcbc-4cd5-bb93-382440f46f16, Date: 2023-01-10T07:52:32.840Z
Instead, I get this:
Id: 00000000-0000-0000-0000-000000000000, Date: 0001-01-01T00:00:00
What am I doing wrong?
CodePudding user response:
From what I tested on my local side, those properties' values were assigned within the constructor.
There are 2 approaches to fix it:
Approach 1: Provide the setter to all properties
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; }
}
Demo
Approach 2: Create a constructor with three parameters
public class ReportRequest
{
...
public ReportRequest(Guid id, string companyId, DateTime requestDate)
{
this.Id = id;
this.CompanyId = companyId;
this.RequestDate = requestDate;
}
...
}
Demo