Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB C# Why can't you use DateTime.Date with IQueryable?

Tags:

c#

mongodb

I have method set up in my MongoDB DAL class.

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);
}

I want to do something simple like

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

However, every time I try, I get an error stating:

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.

I am using the official C# driver version 2.2.4.26.

Is there a way to query on just the date? I've seen posts about using DbFunctions.Truncate, but that is in the EntityFramework libraries, which I would like to stay away from.

like image 878
Dave Avatar asked Jun 01 '16 20:06

Dave


People also ask

What is a MongoDB driver?

The official MongoDB Node. js driver allows Node. js applications to connect to MongoDB and work with data. The driver features an asynchronous API which allows you to interact with MongoDB using Promises or via traditional callbacks.

Is MongoDB paid?

MongoDB is a NoSQL database that is open source. MongoDB is available in two editions. One is MongoDB Open Source, which is free as part of the Open-Source Community, but for the other editions, you must pay a License fee.

Can I use MongoDB with ASP NET?

MongoDB is a document database. Instead of storing data in tables and rows, you store documents in a structure very similar to objects in the memory of your application. The schema is flexible and dynamic.


1 Answers

I had same problem with using Date and i used:

Idea is to use two borders (DateTime.Date is also DateTime but with 0 hours, 0 minutes... and second is next day also with 0 hours, 0 minutes...).

DateTime currentDayStart = DateTime.Now.Date;
DateTime currentDayEnds  = DateTime.Now.Date.AddDays(1);

var result = Retrieve(a => a.SomeDateProperty >= currentDayStart && a.SomeDateProperty < currentDayEnds);

And it works well for me.

like image 163
slavoo Avatar answered Sep 21 '22 06:09

slavoo