I have an ASP.NET API to handle data going to a Mongo database. I need to also send some dynamic / irregular data for a number of documents, that’ll have a couple of extra properties.
I’m trying to use this code from the official tutorial, however I’m getting this error
Unable to cast object of type 'MongoDB.Bson.BsonString' to type 'MongoDB.Bson.BsonBoolean'.
This is the code from the model class:
public class Incident
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }
[BsonElement("Name")]
public string? Name { get; set; }
[BsonExtraElements]
public BsonDocument? ExtraElements { get; set; }
}
This is the controller code
[ApiController]
[Route("api/[controller]")]
public class IncidentController : ControllerBase
{
private readonly IncidentService _incidentService;
public IncidentController(IncidentService incidentService)
{
_incidentService = incidentService;
}
[HttpGet]
public async Task<List<Incident>> Get() =>
await _incidentService.GetAllIncidents();
}
And the service
public async Task<List<Incident>> GetAllIncidents() =>
await _incidents.Find(new BsonDocument()).ToListAsync();
Strangely, the crash also happens in Swagger in POST, before I actually execute the operation.
2
Answers
ExtraElement field is a boolen value in Database but you trying to convert list
Just had this exact error. Turns out I had conflicting references with regards to Bson types.