How to compare date without time in mongodb C# driver?
I try to use this code, bot it don't work.
MongoCursor<Log> query = _logCollection.FindAs<Log>(
Query.And(Query.EQ("Date.getDate()", date.Day),
Query.EQ("Date.getMonth()", date.Month),
Query.EQ("Date.getYear()", date.Year)));
Do you have any ideas?
Query for range of dates, which include your date:
var beginDate = date.Date; // e.g. 7/24/2013 00:00:00
var endDate = beginDate.AddDays(1); // e.g. 7/25/2013 00:00:00
var query = Query.And(Query<Log>.GTE(l => l.Date, beginDate), // including
Query<Log>.LT(l => l.Date, endDate)); // not including
var result = _logCollection.FindAs<Log>(query);
Same with LINQ (MongoDB.Driver.Linq namespace):
var result = from l in _logCollection.AsQueryable()
where l.Date >= beginDate && l.Date < endDate
select l;
Related
How to compare date without time in mongodb C# driver?
I try to use this code, bot it don't work.
MongoCursor<Log> query = _logCollection.FindAs<Log>(
Query.And(Query.EQ("Date.getDate()", date.Day),
Query.EQ("Date.getMonth()", date.Month),
Query.EQ("Date.getYear()", date.Year)));
Do you have any ideas?
Query for range of dates, which include your date:
var beginDate = date.Date; // e.g. 7/24/2013 00:00:00
var endDate = beginDate.AddDays(1); // e.g. 7/25/2013 00:00:00
var query = Query.And(Query<Log>.GTE(l => l.Date, beginDate), // including
Query<Log>.LT(l => l.Date, endDate)); // not including
var result = _logCollection.FindAs<Log>(query);
Same with LINQ (MongoDB.Driver.Linq namespace):
var result = from l in _logCollection.AsQueryable()
where l.Date >= beginDate && l.Date < endDate
select l;
Hi everyone I just want to make a query with Where condition. My default query is.
var list = _Service.GetData(Id);
It returns object list and count is 110.
The sample data from Date property I want to compare is
StartDate:{4.09.2020 13:00:00}
The compare param is like
model.Start={30.11.2020 00:00:00}
My where query is
var list2 = _Service.GetData(Id).Where(x => x.StartDate>= model.Start);
This query returns null. Theese two are DateTime object. Where do I make mistake
My try is get date data from beginning date model.start
NEW
Some more sample data comes from this query
I'm just gonna post dates not other attr.
Datetime StartDate
StartDate {30.09.2020 14:00:00}
StartDate {11.10.2020 13:00:00}
StartDate {24.11.2020 00:03:00}
StartDate {24.11.2020 15:01:00}
...
and more comes from GetData function without filter.
_Service calls context
var list = _Service.GetData(Id);
The other parameter i just want to filter by date is.
DateTime model.Start can be this values
model.Start {20.11.2020 00:00:00}
model.Start {12.10.2020 00:00:00}
model.Start {25.09.2020 00:00:00}
... it's dynamic filter
Also my other try's which returns null to list
var list2 = _Service.GetData(Id).Where(x => x.StartDate>= model.Start);
var list3 = _Service.GetData(Id).Where(x => model.Start.Date >= x.StartDate.Date);
var list4 = _Service.GetData(Id).Where(x => model.Start.Month >= x.StartDate.Month);
var list5 = _Service.GetData(Id).Where(x => x.StartDate.Month >= model.Start.Month);
var list6 = _Service.GetData(Id).Where(x => x.StartDate < DateTime.Now);
I just want to filter data with model.Start to StartDate
I have a snapshot table in my database that holds historical data of appointment availability.
I'm trying to write a LINQ query to get the total number of AvailableSlots within a given date range from the latest snapshot.
Here is what my table looks like:
So with this given data, I'd want my LINQ query to return the sum of AvailableSlots within the date range of 2018-01-01 - 2018-01-02 and with the latest SnapShotTime. So, I'd expect the query to return 4.
Here is what I have so far.
var test = db.snapshots
.GroupBy(g =>
g.AppointmentTime >= startDate &&
g.AppointmentTime <= endDate
).Select(s => s.OrderByDesending(x => x.SnapShotTime).FirstOrDefault();
However, I'm not sure how to put the Sum of available slots into this LINQ query. Any help on writing this query would be appreciated!
i dont see exactly the query that you wrote do, but based on your explanation i think sth like this might have work
var query=db.snapshots
.Where(x=>x.AppointmentTime >= startDate &&
x.AppointmentTime <= endDate)
.GroupBy(x=>x.SnapShotTime)
.OrderByDesending(g=>g.Key)
.Take(1)
.Sum(x=>x.Value.AvailableSlots);
or if it seems so complicated you better first get the latest date like this
var latest=db.snapshots
.OrderByDesending(x => x.SnapShotTime)
.FirstOrDefault().SnapShotTime;
and then get your count like this
var query=db.snapshots
.Where(x=>x.AppointmentTime >= startDate &&
x.AppointmentTime <= endDate &&
x.SnapShotTime==latest)
.Sum(x=>x.AvailableSlots);
Here is what I did.
static void Main(string[] args)
{
DateTime startDate = new DateTime();
DateTime endDate = new DateTime();
List<FakeAppointments> appointmentsFromDatabase = new List<FakeAppointments>();
var appointmentsBetweenStartDateAndEndDate = appointmentsFromDatabase.Where(p => p.SnapshotTime >= startDate && p.SnapshotTime <= endDate).ToList();
int sum = appointmentsBetweenStartDateAndEndDate.Sum(p => p.AvailableSlots);
Console.ReadKey();
}
public class FakeAppointments
{
public DateTime SnapshotTime;
public int AvailableSlots;
}
I have this LINQ query with Entity Framework 6:
var timeCapturesQuery = Context.TimeCaptures
.Where(t =>
&& t.StartDateTime.TimeOfDay < endTime
&& t.EndDateTime.TimeOfDay > startTime);
EndTime and StartTime are parmeters of type TimeSpan, StartDateTime and EndDateTime are columns on the table of datetime.
Unfortunately I get this error when it is run:
The specified type member 'TimeOfDay' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
How can I get a TimeSpan from a DateTime (i.e. the time from datetime in SQL) in this LINQ query?
Looks like DbFunctions.CreateTime is what you're looking for:
When used as part of a LINQ to Entities query, this method invokes the
canonical CreateTime EDM function to create a new TimeSpan object.
So to get results between two times, you can:
var timeCapturesQuery = Context.TimeCaptures.Where(t =>
DbFunctions.CreateTime(t.StartDateTime.Hour, t.StartDateTime.Minute, t.StartDateTime.Second) < endTime &&
DbFunctions.CreateTime(t.EndDateTime.Hour, t.EndDateTime.Minute, t.EndDateTime.Second) > startTime);
The property TimeOfDay does not supported in LINQ to Entities so you can try using SqlFunctions.DatePart method instead.
You should probably also convert your TimeSpans into DateTimes .
I think this should work (assuming the TimeSpans is from the begining of the day):
var now = DateTime.Now;
var today = new DateTime(now.Year, now.Month, now.Day);
var endDateTime = today + endTime;
var startDateTime = today + startTime
var timeCapturesQuery = Context.TimeCaptures.Where(t =>
SqlFunctions.DatePart("timeofday", t.StartDateTime) < SqlFunctions.DatePart("timeofday", endDateTime)
&& SqlFunctions.DatePart("timeofday", t.EndDateTime) > SqlFunctions.DatePart("timeofday", startDateTime));
Edit
As mentioned in the comments the specific property TimeOfTheDay is not supported in DatePart method.
Maybe EntityFunctions.DiffNanoseconds method will work:
var now = DateTime.Now;
var today = new DateTime(now.Year, now.Month, now.Day);
var endDateTime = today + endTime;
var startDateTime = today + startTime
var timeCapturesQuery = Context.TimeCaptures.Where(t =>
EntityFunctions.DiffNanoseconds(t.StartDateTime, endDateTime).Value < 0
&& EntityFunctions.DiffNanoseconds(t.EndDateTime, startDateTime).Value > 0);
Edit2
Another option which is much simpler and I think will work is just to compare the DateTimes.
We've already converted the TimeSpans into DateTimes and we can create a simple condition using LINQ to Entities and it should work because we are not using any of the DateTimes properties.
var now = DateTime.Now;
var today = new DateTime(now.Year, now.Month, now.Day);
var endDateTime = today + endTime;
var startDateTime = today + startTime
var timeCapturesQuery = Context.TimeCaptures.Where(t => t.StartDateTime < endDateTime && t.EndDateTime > startDateTime);
It looks like Linq2db supports it.
https://github.com/linq2db/linq2db/blob/1ff760181717c73859ab3a5519f76943241d460f/Source/Linq/Expressions.cs
Of course it is not very good option to use new ORM.
But I think it is most weak part of EF after performance.
So maybe it is good time to think again.
With Linq2db you can provide custom SQL logic (you need to create own expression). It was never necessary for me, but you can read this for more details.
I have a movie rental application. The company would enter the movie rent date and movie rent end date. Dates can overlap (as you can have many customers). The data in the db is stored as
RecordID FromRentDate ToRentDate
1 2016-10-06 18:00:00.000 2016-10-06 20:00:00.000
2 2015-10-06 18:00:00.000 2015-10-06 20:00:00.000
3 2015-09-29 16:00:00.000 2015-09-30 17:00:00.000
4 2015-09-11 00:00:00.000 2015-09-11 00:00:00.000
5 2015-09-09 10:00:00.000 2015-09-09 14:30:00.000
When the user selects a date (using standard .Net controls) the following code is called
IEnumerable<Event> LiveDates = DataContext.Events.Where(d => d.StartDate.Value >= DateTime.Now);
IEnumerable<DateTime> AllLiveDates = null;
if (LiveDates != null && LiveDates.Count() > 0)
{
DateTime FromRentDate = LiveDates.Where(f => f.StartDate.HasValue).Min(f => f.StartDate).Value;
DateTime ToRentDate = LiveDates.Where(t => t.EndDate.HasValue).Max(f => f.EndDate).Value;
AllLiveDates = Enumerable.Range(0, int.MaxValue)
.Select(x => FromRentDate.Date.AddDays(x))
.TakeWhile(x => x <= ToRentDate.Date)
.Where(x => DataContext.Events.Any(c => x >= c.StartDate && x <= c.EndDate));
}
return AllLiveDates.ToList();
What i would like to happen is when a user selects a date, it gets all the dates from the selected date, to the end date including any inclusive dates where the movie is also out so using the above data, if i select todays date I should get all records back and the dates should be listed as:
2015-09-09
2015-09-11
2015-09-29
2015-09-30
2015-10-06 .... etc
Notice how 2015-09-29, 2015-09-30 are included but 2015-09-30 is not a start date. This is because the length of this movie rental is for 2 days (29 and 30 September).
The problem i am experiencing with the above code is that it only returns 1 date. Debugging it it seems to go into AllLiveDates code and something is removing the other dates but not sure what?
You could try something like this
var dateList = new List<DateTime>();
foreach (var ld in LiveDates)
{
for (var dt = ld.StartDate.Date; dt <= ld.EndDate.Date; dt = dt.AddDays(1))
{
dateList.Add(dt);
}
}
dateList = dateList.Distinct().ToList();
dateList = dateList.Sort((a, b) => a.CompareTo(b));
The issue appears to be that you are comparing a date value with a date and time.
Take for example the date 2015-09-09. When you compare that to the DateTime values in your table you should get zero matches, because the DateTime value 2015-09-09 00:00:00.0000 does not lie between the start and end DateTime values of any of your data points.
You will need to strip the time portions of your data points to get the comparison to work the way you want. Fortunately LINQ to SQL supports the .Date property of DateTime values, so this should work:
Try this:
AllLiveDates = Enumerable.Range(0, int.MaxValue)
.Select(x => FromRentDate.Date.AddDays(x))
.TakeWhile(x => x <= ToRentDate.Date)
.Where(x => DataContext.Events.Any(c => x >= c.StartDate.Value.Date && x <= c.EndDate.Value.Date));
Just don't look at the generated SQL... it's not pretty.