如何修复:无法施放类型的对象' mongodb.bson.bsonarray'要键入mongodb.bson.bsonboolean'
我有一个ASP.NET API来处理到Mongo数据库的数据。我还需要为许多文档发送一些动态 /不规则数据,这些数据将具有几个额外的属性。
我正在尝试使用 this cod e从官方教程,但是我遇到了此错误,
Unable to cast object of type 'MongoDB.Bson.BsonString' to type 'MongoDB.Bson.BsonBoolean'.
这是模型类中的代码:
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; }
}
这是控制器代码
[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();
}
,并且
public async Task<List<Incident>> GetAllIncidents() =>
await _incidents.Find(new BsonDocument()).ToListAsync();
在我实际执行操作之前,崩溃也奇怪地发生在帖子中。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我遇到了一个类似的问题,并通过返回
json
而不是bsondocument
来解决它。在您的情况下,您可以将列表转换为json
。I faced a similar problem and I solved it by returning
Json
instead ofBsonDocument
. In your case you can transform the list toJson
.超元素字段是数据库中的布尔值,但您尝试转换列表
ExtraElement field is a boolen value in Database but you trying to convert list
只是有这个确切的错误。事实证明,关于BSON类型,我的参考存在冲突。
Just had this exact error. Turns out I had conflicting references with regards to Bson types.