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
Related
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?
This is mysql query:
select
convert(date,convert(char(11),[Bill Date])) as date,
SUM(Amount) as total from Bills
group by [Bill Date]
order by date asc
What will be its LINQ to SQL with entitiy?
You can use LINQ GroupBy method with Sum method
You may use the DbFunctions.TruncateTime method on the BillDate datetime field to eliminate the timestamp part when grouping on the date (assuming you want to get total for each day)
var groupedSum= db.Bills.GroupBy(x => DbFunctions.TruncateTime(x.BillDate))
.Select(x => new
{
Total= x.Sum(g => g.Amount),
Date = x.Key
}).OrderBy(f=>f.Date).ToList();
This gives you a list of anonymous objects with a Day property and a Total property.
Assuming db is your db context object and Bills is a property of type DbSet<Bill>
DbFunctions.TruncateTime method is in System.Data.Entity namespace. So make sure you have a using statement to import that.
I have to make in c# a query with linq to sql. I can handle it in sql but in linq to
sql is the result not what I wanted to get.
So there is a table with:
a day, in datetime with date and time
and a kind of id
I have to count the ids for each date, the time isn't important. So the result
should be something like:
day: 2013-11-12 amountIDs: 4
People said to me, I can make a select new query and in this query I can set the day
and could count the ids, or I make a group by day. I read similar question, but it doesn't work in my case.
Could somebody help me?
I tried it with the statement below, but the days have to be grouped, so now the output is foreach datetime, like this
day: 12.12.2013 12:00:00 amountIDs: 1
day: 12.12.2013 12:10:10 amountIDs: 1
In sql I made this statement:
SELECT CONVERT(VARCHAR(20), data.dayandtime, 106) AS day, count(data.amountIds) as ids
FROM data
WHERE ( data.dayandtime >= DATEADD(day, -28, getdate()) AND (data.type = 100) AND (data.isSomething = 0) )
GROUP BY CONVERT(VARCHAR(20), data.dayandtime, 106), data.isSomthing and it works.
I saw similar cases, where people made a : from-select-new xyz statement, than I made a view of it and tried to group just the view. Like this
var query = data.GroupBy(g => g.day.Value).ToList();
var qry = from data in dbContext
group data by data.day into dataGrpd
select new
{
day= dataGrpd.Key,
amountIDs= dataGrpd.Select(x => x.Id).Distinct().Count()
};
Check This
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.
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