gpt4 book ai didi

c# - MongoDB C# 为什么不能将 DateTime.Date 与 IQueryable 一起使用?

转载 作者:可可西里 更新时间:2023-11-01 09:35:01 25 4
gpt4 key购买 nike

我在我的 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);
}

我想做一些简单的事情,比如

var result = Retrieve(a => a.SomeDateProperty.Date >= startDate && a.SomeDateProperty.Date <= endDate);

但是,每次尝试时,我都会收到一条错误消息:

An exception of type 'System.InvalidOperationException' occurred in MongoDB.Driver.dll but was not handled in user code

Additional information: {document}{SomeDateProperty}.Date is not supported.

我使用的是官方 C# 驱动程序版本 2.2.4.26。

有没有办法只查询日期?我看过关于使用 DbFunctions.Truncate 的帖子,但那是在 EntityFramework 库中,我想远离它。

最佳答案

我在使用 Date 时遇到了同样的问题,我使用了:

想法是使用两个边框(DateTime.Date 也是 DateTime 但有 0 小时、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);

它对我来说效果很好。

关于c# - MongoDB C# 为什么不能将 DateTime.Date 与 IQueryable 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37577998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com