How query Db with datetimeoff using entityframework - c#

I want to query the database with a column with datetimeoffset(7). This takes startDate and endDate as seen in the code below.
my URL is something like this
http://localhost:60018/v1/getDepartPoints?startDate=2015-08-08&endDate=2015-08-08
Below is my query that returned 0 list
var result = Db.Points.Where(t => t.DepartureTime > startDate && t.DepartureTime < endDate).ToList();
Below is the sql query that works
SELECT * FROM [dbo].[Points] WHERE DepartureTime = '2015-08-08 04:35:00.0000000 -10:00'
This below query didnt work as I expected after casting to datetime
SELECT * FROM [dbo].[Points] WHERE cast(DepartureTime as datetime) = '2015-08-08'
How can I make my query return the expected list with the datetime passed to datetimeoffset in the Database?

Related

Entity Framework sqlquery pass current date

I want to call a SQL query with joins to Oracle database. For each table in query i need to check a field for SYSDATE
SELECT
per.PERSON_ID
...
FROM
PERSON_V per
JOIN
SALARY sal ON sal.PERSON_ID = per.PERSON_ID
AND sal.EFF_START_DATE <= SYSDATE
AND sal.EFF_END_DATE > SYSDATE
...
WHERE
per.EFF_START_DATE <= SYSDATE
AND per.EFF_END_DATE > SYSDATE
In my code I do as below
var sql = #"SELECT
per.PERSON_ID
...
FROM PERSON_V per
JOIN SALARY sal
ON sal.PERSON_ID = per.PERSON_ID AND sal.EFF_START_DATE <= GETDATE() AND sal.EFF_END_DATE > GETDATE()
...
WHERE per.EFF_START_DATE <= GETDATE() AND perEFF_END_DATE > GETDATE()";
var oracle_employees = _oracleDbContext.Database.SqlQuery<List<EmployeeDetails>>(sql);
I get GETDATE is invalid identifier. I tried with SYSDATE, DateTime.Now, date as string, none of them worked. What is the right way to pass date to the query from code.

How to write linq query from sql query using LINQ?

I have a table with two columns like BookingArrivedEnquiredTime with varchar datatype and datetime BookingArrivedEnquiredDateTime. When I execute this query in SQL Server the result give perfect with time sorted order
the sql query will be like
select BookingArrivedEnquiredTime from BookingArriveds where BookingArrivedEnquiredDateTime='2015-02-17 00:00:00.000'
order by CAST(('01/01/2000 ' + BookingArrivedEnquiredTime) AS DATETIME)
and it gives out put like this
11:27 AM
11:47 AM
11:53 AM
12:13 PM
12:50 PM
02:02 PM
02:47 PM
03:04 PM
03:16 PM
When i try this query into using linq
public ViewResult Index1(DateTime? Startdate)
{
Startdate = DateTime.Now.Date;
var fm = DateTime.Parse("01/01/2000");
var qr = from item in db.BookingArriveds
where item.BookingArrivedEnquiredDateTime == Startdate
orderby DateTime.Parse("01/01/2000 " +
item.BookingArrivedEnquiredTime.ToString())
select item;
return View(qr);
}
but it gives error like this
LINQ to Entities does not recognize the method 'System.DateTime Parse(System.String)' method, and this method cannot be translated
into a store expression.
where is wrong and I need help for how to rewrite above sql query to linq query also casting from varchar to datetime in linq?
As others have answered, this breaks because .ToString fails to translate to relevant SQL on the way into the database.
However, Microsoft provides the SqlFunctions class that is a collection of methods that can be used in situations like this.
For this case, what you are looking for here is SqlFunctions.StringConvert:
public ViewResult Index1(DateTime? Startdate)
{
Startdate = DateTime.Now.Date;
var fm = DateTime.Parse("01/01/2000");
var qr = from item in db.BookingArriveds
where item.BookingArrivedEnquiredDateTime == Startdate
orderby SqlFunctions.StringConvert("01/01/2000 " +
item.BookingArrivedEnquiredTime.ToString())
select item;
return View(qr);
}
Good when the solution with temporary variables is not desirable for whatever reasons.
You have two options:
you can do the casting and sorting on client:
db.BookingArriveds
.Where(item => item.BookingArrivedEnquiredDateTime == Startdate)
.AsEnumerable()
.OrderBy(item => DateTime.Parse("01/01/2000 " + item.BookingArrivedEnquiredTime);
or you can use SqlFunctions.DatePart to do the cast in Sql server: https://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions(v=vs.110).aspx
EDIT: DatePart function is not suitable, because it gives you only date part. To do the casting in SQL server, you should define your own sql function: https://msdn.microsoft.com/en-us/library/vstudio/dd456847(v=vs.100).aspx
The question is, why are you storing BookingArrivedEnquiredTime in a varchar column. I believe it should be part of BookingArrivedEnquiredDateTime or it should be stored as integer or numeric column

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)

Query to return data from SQL Server table based on date criteria

I have the following piece of code in C# that I use to select some rows from a SQL Server table based on a date criteria.
DateTime From, DateTime To
SqlParameter[] oParam = new SqlParameter[3];
oParam[0] = new SqlParameter("#From", From.Date);
oParam[1] = new SqlParameter("#To", To.Date);
DataTable dt = clsDatabaseHistory.ExecuteReader("SELECT * FROM tblHistory WHERE Date_Requested BETWEEN #From and #To", oParam);
If for example From=18/08/2011 and To=18/08/2011 and there is data in the table tblHistory that has the Date_Requested value as 18/08/2011 the query does not return it.
But if I change the value of To from 18/08/2011 to To=19/08/2011 the query returns me all the values from the table that have a Date_Requested value of 18/08/2011, but none from the 19/08/2011.
How can something like that be possible and what query should I use to return rows where the date field is between date1 and date2.
Something like :
select * rows where datevalue >= date1 and datevalue <= date2
Thank you.
Change your query to use >= and <
select * rows where datevalue >= date1 and datevalue < date2 + 1
I bet your Date_Requested in your table also has some time associated with it - so it probably really is 18/08/2011 14:37 or something like that.
The BETWEEN clause will be selecting anything between 18/08/2011 00:00:00 and 18/08/2011 00:00:00 - basically nothing.
What you need to take into account when working with DATETIME is the fact there's always also TIME involved!
If you want everything for today, you need to use:
BETWEEN `18/08/2011 00:00:00` AND `18/08/2011 23:59:59`
With those two values, you should get all rows with a Date_Requested of today.
OR: in SQL Server 2008 and newer, you could also use the DATE column type which stores date only - no time portion involved. In that case, you should be fine with your query values.
From.Date and To.Date gets the date portion on c# side ignoring the time portion; you need to do something similar on the database side.
Try
"SELECT * FROM tblHistory WHERE cast(Date_Requested as DATE) BETWEEN #From and #To"
to remove the time portion.
EDIT:
as explained in this answer, you could change #To param value to
oParam[1] = new SqlParameter("#To", To.Date.AddDays(1));
You need to account for time (not just date). One way I handle that is like this:
SELECT
...
WHERE CONVERT(varchar(8), date_begin, 112) <= convert(varchar(8), #to, 112)
This converts dates to YYYYMMDD format (with no time), which is very easy to use in <, >, = comparrisons.
Ok, thanks to you all, i've done the following thing
oParam[2] = new SqlParameter("#To", To.Date.AddDays(1));
and used the following select
SELECT * from MyTable WHERE CONVERT(varchar(8), Date_Requested, 112) >= CONVERT(varchar(8), #From, 112) and CONVERT(varchar(8), Date_Requested, 112) < CONVERT(varchar(8), #To, 112)
Datetime variables must be converted to be compared.
Thanks all!

Date function problem in SQL and Linq

I issued a SQL on SQL Server 2000:
select * from Employee where LastUpdateDate >=DateAdd(yyyy,-1,Getdate())
It works fine and got some records.
Then I write a Linq for the same purpose:
EntityQuery<Employee> query = from e in ctx.GetEmployeeQuery()
where e.DateCreated >= DateTime.Today.AddYears(-1)
but I got null from the result.
How to fix it?
Linq to Entities doesn't support the AddYear method. It does not know how to translate this into SQL. The solution is to precalc the value.
var targetDate = DateTime.Now.AddYears(-1)
EntityQuery<Employee> query = from e in ctx.GetEmployeeQuery()
where e.DateCreated >= targetDate

Categories

Resources