Search code examples
c#mongodbmongodb-querymongodb-.net-driver

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


I am using latest c# mongo driver in my .net core 2.0 app. I have this error in my code

Cannot deserialize a 'String' from BsonType 'Int64'..

But mongo query doesn't threw any exception. Here is the find method in my repository.

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

Here is the handler code

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

Code run successfully but shows error inside data returned from this query.

enter image description here

enter image description here

I want to throw this exception so that my framework can handle it. Is their any settings related to this.

Need help.

Thanks


Solution

  • To get a FormatException from MongoDB driver you need to fetch the data from the database while in your code you're only building a query. Extension method .ToEnumerable() you're using is not hitting the database so you won't get any results at that point. The documentation says that it:

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

    So to enumerate a cursor you can for instance run foreach or ToList on it. Otherwise it's just a database query without any results. To fix that you can change your Find method body:

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