我在MongoDB DAL类中设置了方法。
public IQueryable<MyModel> Retrieve(Expression<Func<MyModel, bool>> expression)
{
if (!BsonClassMap.IsClassMapRegistered(typeof(MyModel)))
{
DoMapping();
}
var client = new MongoClient(MongoConnectionString);
var database = client.GetDatabase("DatabaseName");
var documents = database.GetCollection<MyModel>("MyModelTable");
return documents.AsQueryable<MyModel>().Where(expression);
}
Run Code Online (Sandbox Code Playgroud)
我想做一些简单的事情
var result = Retrieve(a => a.SomeDateProperty.Date >= startDate && a.SomeDateProperty.Date <= endDate);
Run Code Online (Sandbox Code Playgroud)
但是,每次尝试时,都会显示错误消息:
MongoDB.Driver.dll中发生类型为'System.InvalidOperationException'的异常,但未在用户代码中处理
其他信息:{document} {SomeDateProperty}。不支持日期。
我正在使用官方的C#驱动程序版本2.2.4.26。
有没有办法只查询日期?我已经看过有关使用DbFunctions.Truncate的帖子,但是那是在EntityFramework库中,我希望远离。
我在使用时遇到了同样的问题,我曾经Date使用过:
想法是使用两个边界(DateTime.Date也是DateTime0小时0分钟...,第二天也是第二天0小时0分钟...)。
DateTime currentDayStart = DateTime.Now.Date;
DateTime currentDayEnds = DateTime.Now.Date.AddDays(1);
var result = Retrieve(a => a.SomeDateProperty >= currentDayStart && a.SomeDateProperty < currentDayEnds);
Run Code Online (Sandbox Code Playgroud)
它对我来说很好。