无法使用.Date

时间:2016-10-13 13:56:35

标签: c# mongodb datetime mongodb-.net-driver

我正在尝试从带有日期过滤器的mongoDB集合中读取(只有日期,时间应该被忽略):

var filterDefinition = Builders<SomeClass>.Filter.Eq(p => p.SomeDateTimeProperty.Date, DateTime.Now.Date);
using (var cursor = await _someCollection.FindAsync(filterDefinition))
{ ... }

SomeClassSomeDateTimeProperty属性如下所示:

[BsonIgnoreExtraElements]
[Serializable]
public class ReportConfiguration
{
    ...
    public DateTime SomeDateTimeProperty { get; set; }
    ...
}

尝试InvalidOperationException时,代码会抛出.FindAsync()

  

发生了'System.InvalidOperationException'类型的异常   MongoDB.Driver.dll但未在用户代码中处理   信息:无法确定p的序列化信息   =&GT; p.SomeDateTimeProperty.Date

如果我删除过滤器中的.Date部分(p.SomeDateTimeProperty.Date,DateTime.Now.Date),一切都有效,但我需要一个yyyy \ mm \ dd比较,无论hh \ mm。

Stacktrace说:

at MongoDB.Driver.ExpressionFieldDefinition`2.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.SimpleFilterDefinition`2.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.MongoCollectionImpl`1.CreateFindOperation[TProjection](FilterDefinition`1 filter, FindOptions`2 options)
at MongoDB.Driver.MongoCollectionImpl`1.FindAsync[TProjection](FilterDefinition`1 filter, FindOptions`2 options, CancellationToken cancellationToken)
at MongoDB.Driver.IMongoCollectionExtensions.FindAsync[TDocument](IMongoCollection`1 collection, FilterDefinition`1 filter, FindOptions`2 options, CancellationToken cancellationToken)
at [...]

可能是什么问题?

2 个答案:

答案 0 :(得分:1)

您是否考虑过使用Lt和Gt运算符的from子句

 var b = Builders<SomeClass>.Filter;
 var date = DateTime.UtcNow.Date;
 var filter = b.And(
        b.Gte(x => x.SomeDateTimeProperty, date), 
        b.Lt(x => x.SomeDateTimeProperty, date.AddDays(1))
        );
 ...

答案 1 :(得分:0)

驱动程序不知道如何在两个日期之间序列化Eq表达式。

尝试对两个日期部分执行ToString():

var filterDefinition = Builders<SomeClass>.Filter.Eq(p => p.SomeDateTimeProperty.Date.ToString(), DateTime.Now.Date.ToString());

如果这不起作用,请尝试以下方法:

var date = DateTime.Now.Date.ToString();    
var docs = _someCollection.asQueryable().Where(p => p.SomeDateTimeProperty.Date.ToString() == date);