MongoDB C# Driver Find 未抛出 System.FormatException 反序列化错误并运行成功

MongoDB C# Driver Find not throwing System.FormatException Deserialization error and runs successfully

我在我的 .net core 2.0 应用程序中使用最新的 c# mongo 驱动程序。我的代码中有这个错误

无法从 BsonType 'Int64'..

反序列化 'String'

但是 mongo 查询没有抛出任何异常。这是我存储库中的查找方法。

        /// <summary>
        /// find entities
        /// </summary>
        /// <param name="filter">expression filter</param>
        /// <returns>collection of entity</returns>
        public virtual IEnumerable<T> Find(Expression<Func<T, bool>> filter)
        {
            return Collection.Find(filter).ToEnumerable();
        }

        /// <summary>
        /// find entities
        /// </summary>
        /// <param name="filter">expression filter</param>
        /// <returns>collection of entity</returns>
        public Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> filter)
        {
            return Task.Run(() => Find(filter));
        }

这是处理代码

public async Task<object> Handle(GetQuestionBySurveyIdAndCodeQuery request, CancellationToken cancellationToken)
    {
      var result = await _context.Question.FindAsync(x => x.SurveyId.Equals(request.SurveyId));
      return result;
    }

代码 运行 成功,但从该查询返回的数据中显示错误。

我想抛出这个异常,以便我的框架可以处理它。他们的任何设置是否与此相关。

需要帮助。

谢谢

要从 MongoDB 驱动程序中获取 FormatException,您需要 从数据库中获取 数据,而在您的代码中,您只是构建一个查询.您正在使用的扩展方法 .ToEnumerable() 未访问数据库,因此此时您不会获得任何结果。文档 says 它:

Wraps a cursor in an IEnumerable that can be enumerated one time.

因此,要枚举游标,您可以在其上使用 运行 foreachToList 等。否则它只是一个没有任何结果的数据库查询。要解决这个问题,您可以更改 Find 方法主体:

public virtual IEnumerable<T> Find(Expression<Func<T, bool>> filter)
{
    return Collection.Find(filter).ToList();
}