Entity Framework Getting current date rows(while time in that day) - c#

I have table that the value of dateime is like this
2021-12-08 10:10:54.657
2021-12-08 10:10:41.567
2021-12-08 10:09:51.960
2021-12-08 10:10:54.657
2021-12-08 10:10:41.567
2021-12-08 10:09:51.960
2021-12-08 10:10:54.657
and I want to get that day or today (now is 8 dec 2021) . So i have tried using EF in controller :
ViewBag.CByUserToday = _db.ArrayDatas.Where(a => a.CreatedBy == user && a.CreatedDate == DateTime.Today.Date).Count();
But i still did not get the rows. When i tried to debug DateTime.Today.Date , it's said DateTime.Today = {09/12/2021 00:00:00} . But when i tried to update that createddate to '2021-12-09 00:00:00.000' it can be retrieved.
So, how to retrieve that rows that i have created today(ignoring the time) ?

Check that the column is greater than or equal to today, and less than tomorrow:
DateTime today = DateTime.Today;
DateTime tomorrow = today.AddDays(1);
ViewBag.CByUserToday = _db.ArrayDatas
.Where(a => a.CreatedBy == user
&& a.CreatedDate >= today
&& a.CreatedDate < tomorrow)
.Count();
That way, your DBMS will be able to use a suitable index on the CreatedBy and CreatedDate columns to satisfy your query.
It's usually preferable to avoid calling functions on a column when you're trying to filter it, since this means the query is not SARGable. However, according to this thread on DBA, casting a datetime/datetime2 column to date is SARGable, at least in Microsoft SQL Server.

Related

LINQ Query Syntax for Self Join

Table Jobs is the primary file record with the JobId.
Table PostThr records the scheduling of when the jobs begin and end. There are 5 fields: ID, FK, ThrDate(DateTime), ThrTime(TimeSpan), and ThrText(string). There is one entry for a job start and another for the job end. The jobs do not last for more than one date, ie overnight.
The goal is to show how many jobs are active at the same time, rather within the same hour block, using the records in PostThr. I feel like this is a LINQ query, some sort of join, and I'm not sure of the syntax.
DateTime givenDate = DateTime.Parse("7/2/22");
DateTime givenTime = TimeSpan.Parse("9:00");
int y = _context.PostThrs.Where(m =>
m.ThrDate == dateZero &&
((
m.ThrText == "CONFIRM START-" &&
m.ThrTime >= myTime
) && (
m.ThrText == "CONFIRM END-" &&
m.ThrTime <= myTime
))
).Count();
Try to match the date only in the date condition because when we are usually comparing date it also compares the time as well. Hope you find this helpful

Proper use of DbFunctions.CreateDateTime()

I've got a database tabel 'DateExcluded' containing 3 int columns : Year, Month and Day, the latter being the daynumber of the month. I want their combination evaluated in an entity query, to retrieve all rows before one year from current date like so :
var l =
(from p in c.DateExcluded
where
DbFunctions.CreateDateTime(p.Year, p.Month, p.Day, null, null, null)
<= DateTime.Now.AddYears(1)
select p).ToList();
This query always returns 0 columns which it shouldn't. Wrong use of DbFunctions.CreateDateTime?
I've got a database tabel 'DateExcluded' containing 3 int columns : Year, Month and Day.
Don't ever create a column for each year, month and day
You're creating a non-sargable query, also know as the worst performing query you can create.
The correct way is to actually use a DateTime field. Then your query is just correct without any incorrect math possible.
var l =
(from p in c.DateExcluded
where
c.DateExcluded < DateTime.Now.AddYears(1).AddDay(1)
select p)
.ToList();
If you still want to use DbFunctions.CreateDateTime, avoid null values as it won't work correctly (see why in comment by Ole EH Dufour).
You should pass 0 instead of null, like this:
DbFunctions.CreateDateTime(p.Year, p.Month, p.Day, 0, 0, 0)

Check that a given date does not lie between two existing dates inside a datatable

I have one table which can store student leave start date and end date
like so:
StudentID Age startDate EndDate
1 14 5/05/2013 7/05/2013
4 17 4/04/2012 8/10/2012
I need to check to see if any new leave which is applied for doesn't fall in the range of leave already arranged for that student. For example, for the student with ID = 1, they should not be able to apply for leave which starts on 6/05/2013.
I'm using c# and am looking for a solution which uses SQL or LINQ.
normal SQL
Select count(*) from table where StudentID = 'parameterID' and startDate <= 'Parameter_StartDate' and EndDate <='Parameter_EnsDate';
DateTime dtApplied;
var allDates = yourDt.Rows.Cast<DataRow>().Where(x => dtApplied >= x.Field<DateTime>("startDate") && dtApplied <= x.Field<DateTime>("endDate"));
However I would consider using BETWEEN in SQL if I were you.
You can try this :
var result = dt.AsEnumerable().Where(r =>((int)r["StudentID"])==stdID &&
(DateTime)r["startDate"]<=yourStartDate &&
(DateTime)r["EndDate"]=YourEndDate))
.FirstOrDefault();
Or you can do this also:
string query="ID=1 AND startDate<=yourStratDate AND EndDate>=yourEndDate";
DataRow [] dr=dt.Select(strQuery);
select student_id From TableName Where Student_id = 1 and #dateToCheck not( between startdate and enddate)

C# LINQ Oracle date Functions

I am trying to generate a sql statement to be used in Oracle11g, using linq.
The problem arises when using dates:
C# code:
DateTime convertedMinStartDateForEvent = Convert.ToDateTime(minStartDateForEvent);
DateTime convertedMinEndDateForEvent = Convert.ToDateTime(minEndDateForEvent);
var query = (from myTableRec in uow.myTable
where myTableRec.startdate >= convertedMinStartDateForEvent && myTableRec.endDate < convertedMinEndDateForEvent
The SQL generated by linq gives
SELECT *
FROM <table>
WHERE start_date > '24/11/2012 00:00:00' and end_date < '28/11/2012 00:00:00'
This causes an oracle error: ORA-01830 - date format picture ends before converting entire input string
Adding TO_DATE to the query fixes the ORA-01830, as it is converting the string to a oracle date whilst now knowing the date format.
SELECT *
FROM <table>
WHERE start_date > TO_DATE('24/11/2012 00:00:00','DD/MM/YYYY HH24:MI:SS') and end_date < TO_DATE('28/11/2012 00:00:00','DD/MM/YYYY HH24:MI:SS')
So, is there a way to add TO_DATE to LINQ (for oracle)?
If not, please tell me how to work around this issue.
Thanks
I have no idea whether this will actually work, but this is what I'd try:
var query = from myTableRec in uow.myTable
where myTableRec.startdate >= convertedMinStartDateForEvent.Date
&& myTableRec.endDate < convertedMinEndDateForEvent.Date
(I've edited the query to refer to myTableRec - I suspect the code you posted wasn't your real code.)
You may even want to add the Date part to all references:
var query = from myTableRec in uow.myTable
where myTableRec.startdate.Date >= convertedMinStartDateForEvent.Date
&& myTableRec.endDate.Date < convertedMinEndDateForEvent.Date
Hopefully this will add the appropriate TO_DATE calls to the generated SQL. I agree with the comment that this sounds like a bug in the LINQ provider though.

Query Dates From SQLServer in C#?

I am building a web application that is going to show the upcoming birthdays of a list of people stored in a SQL Server 2008 DB. I can't figure out how to query all records in the DB that are within 30 days of today's date.
Here's what I have so far:
using (HumanResourcesDB db = newH umanResourcesDB(ConfigurationManager.ConnectionStrings["HumanResourcesDB"].ConnectionString))
{
DateTime todaysDate = DateTime.Now;
List<Employee> record =
(from tab in db.Employees
where tab.Birthday between DateTime.Now and todaysDate.AddDays(30)
select tab).ToList();
this.grdBirthdays.DataSource = record;
this.grdBirthdays.DataBind();
}
of course the "between" and "and" don't work that's what I need filled in. I've searched the net for a little while to no avail. Any help?
Just use a greater than and less than
using (HumanResourcesDB db = newHumanResourcesDB(ConfigurationManager
.ConnectionStrings["HumanResourcesDB"].ConnectionString))
{
List<Employee> record = (from tab in db.Employees
where tab.Birthday >= DateTime.Today
&& tab.Birthday < DateTime.Today.AddDays(31)
select tab).ToList();
this.grdBirthdays.DataSource = record;
this.grdBirthdays.DataBind();
}
Also I should mention that I have used DateTime.Today rather than DateTime.Now because today represents the start of the day as 00:00:00.000. If someones birthday is set to whatever today is at 00:00:00.000 and you have used DateTime.Now (let's assume it's 8:00 in the morning). There birthday will not be included in this range because it is considered before "now".

Categories

Resources