【问题标题】:How to fix : Unable to cast object of type 'MongoDB.Bson.BsonArray' to type 'MongoDB.Bson.BsonBoolean'如何修复:无法将类型为 \'MongoDB.Bson.BsonArray\' 的对象转换为类型为 \'MongoDB.Bson.BsonBoolean\'
【发布时间】:2023-02-07 15:17:45
【问题描述】:

我有一个 ASP.NET API 来处理进入 Mongo 数据库的数据。我还需要为一些文档发送一些动态/不规则数据,这些数据会有一些额外的属性。

我正在尝试使用官方教程中的this code,但是我收到了这个错误

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();

奇怪的是,在我实际执行操作之前,崩溃也发生在 POST 中的 Swagger 中。

【问题讨论】:

  • 什么是_incidents?是MongoCollection&lt;Incident&gt;类型吗?同时我认为 await _incidents.Find().ToListAsync(); 而不是 await _incidents.Find(new BsonDocument()).ToListAsync(); 如果没有过滤器,则不需要 new BsonDocument() 的提供。虽然标题和问题中的错误消息不同。
  • 即使发布错误是相同的,只是它也会使 Swagger 崩溃,这是可以预料的

标签: c# asp.net mongodb asp.net-web-api bson


【解决方案1】:

额外元素字段是数据库中的布尔值,但您试图转换列表

【讨论】:

  • 但即使是空数据库集合或尊重值类型的数据库集合(使用 Compass 手动上传),也会发生这种情况。
【解决方案2】:

刚刚有这个确切的错误。原来我对 Bson 类型的引用有冲突。

【讨论】:

  • 我删除了问题,请将其移至评论中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-17
  • 1970-01-01
  • 2022-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多