[英]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. 我在.net core 2.0应用程序中使用最新的c#mongo驱动程序。 I have this error in my code 我的代码中有此错误
Cannot deserialize a 'String' from BsonType 'Int64'. 无法从BsonType'Int64'反序列化'String'。 . 。
But mongo query doesn't threw any exception. 但是mongo查询不会引发任何异常。 Here is the find method in my repository. 这是我的存储库中的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));
}
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. 代码成功运行,但显示此查询返回的数据内部错误。
I want to throw this exception so that my framework can handle it. 我想抛出此异常,以便我的框架可以处理它。 Is their any settings related to this. 是他们与此相关的任何设置。
Need help. 需要帮忙。
Thanks 谢谢
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. 要从MongoDB驱动程序获取FormatException
,您需要从数据库中获取数据,而在代码中仅构建查询。 Extension method .ToEnumerable()
you're using is not hitting the database so you won't get any results at that point. 您正在使用的扩展方法.ToEnumerable()
不会访问数据库,因此此时您将无法获得任何结果。 The documentation says that it: 该文档说 :
Wraps a cursor in an IEnumerable that can be enumerated one time. 将游标包装在可以枚举一次的IEnumerable中。
So to enumerate a cursor you can for instance run foreach
or ToList
on it. 因此,要枚举游标,您可以在其上运行foreach
或ToList
。 Otherwise it's just a database query without any results. 否则,它只是一个没有任何结果的数据库查询。 To fix that you can change your Find
method body: 要解决此问题,您可以更改Find
方法的正文:
public virtual IEnumerable<T> Find(Expression<Func<T, bool>> filter)
{
return Collection.Find(filter).ToList();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.