使用像这样的poco
public class Log
{
public ObjectId Id { get; set; }
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime DateTime { get; set; }
public LogLevel Level { get; set; }
[BsonIgnoreIfNull]
public TraceLogEntity Exception { get; set; }
}
然后使用
从Mongo m获取值var filter = Builders<Log>.Filter.Empty;
filter &= Builders<Log>.Filter.Where(l => l.DateTime.Equals(DateTime.Now.ToShortDateString()));
var collection = _context.Log.Find(filter).Limit(100).ToList();
我不知道为什么我得到对象引用而不是设置为对象的实例 如果我评论日期时间检查,那么每件事都有效
可以帮助我解决问题
堆栈跟踪
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Serialize(IBsonSerializer serializer, BsonSerializationContext context, Object value)
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.ToBsonValue(IBsonSerializer serializer, Object value)
at MongoDB.Driver.Linq.Translators.PredicateTranslator.TranslateComparison(Expression variableExpression, ExpressionType operatorType, ConstantExpression constantExpression)
at MongoDB.Driver.Linq.Translators.PredicateTranslator.TranslateEquals(MethodCallExpression methodCallExpression)
at MongoDB.Driver.Linq.Translators.PredicateTranslator.TranslateMethodCall(MethodCallExpression methodCallExpression)
at MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression node)
at MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression node, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate[TDocument](Expression`1 predicate, IBsonSerializer`1 parameterSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.ExpressionFilterDefinition`1.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.MongoCollectionImpl`1.CreateFindOperation[TProjection](FilterDefinition`1 filter, FindOptions`2 options)
at MongoDB.Driver.MongoCollectionImpl`1.FindSync[TProjection](FilterDefinition`1 filter, FindOptions`2 options, CancellationToken cancellationToken)
at MongoDB.Driver.FindFluent`2.ToCursor(CancellationToken cancellationToken)
at MongoDB.Driver.IAsyncCursorSourceExtensions.ToList[TDocument](IAsyncCursorSource`1 source, CancellationToken cancellationToken)
保存在DB中的值
答案 0 :(得分:1)
2.4.2中隐式转换和空引用似乎存在错误。两个错误都在2.4.3
中修复https://jira.mongodb.org/browse/CSHARP-1922&amp; https://jira.mongodb.org/browse/CSHARP-1894
顺便说一下,我应该注意到您正在尝试将字符串日期与表达式中有效的日期类型进行比较,C#驱动程序负责将其转换为日期。
你有几个选择。
升级到2.4.3
其他选项是使用日期类型。以下两种变体在2.4.2中都可以正常工作。
filter &= Builders<Log>.Filter.Where(l => l.DateTime.Equals(DateTime.Now));
filter &= Builders<Log>.Filter.Eq(l => l.DateTime, DateTime.Now);