MongoDB C#驱动程序查找未抛出System.FormatException反序列化错误并成功运行

问题描述 投票:1回答:1

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

无法从BsonType'Int64'反序列化'String'..

但mongo查询不会引发任何异常。这是我的存储库中的find方法。

        /// <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;
    }

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

enter image description here

enter image description here

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

需要帮忙。

谢谢

c# mongodb mongodb-query mongodb-.net-driver
1个回答
0
投票

要从MongoDB驱动程序获取FormatException,您需要从数据库中获取数据,而在您的代码中,您只需构建查询。你正在使用的扩展方法.ToEnumerable()没有访问数据库,所以你不会得到任何结果。它的文件says

将游标包含在可以枚举一次的IEnumerable中。

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

public virtual IEnumerable<T> Find(Expression<Func<T, bool>> filter)
{
    return Collection.Find(filter).ToList();
}
© www.soinside.com 2019 - 2024. All rights reserved.