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
Related
I want convert following LINQ query to SQL query.
var ACTIVITY_ROYALITY_MONTH = from m in db.MiningPermit
join pm in db.Permit_Mineral on m.MINING_PERMIT_ID equals pm.MINING_PERMIT_ID
join r in db.Royality on pm.Permit_Minerals_ID equals r.Permit_Minerals_ID
where r.ORDER_ID == 0 // NULL in server
orderby r.YEAR, r.MONTH
group r by new { m.MINING_PERMIT_ID , r.YEAR, r.MONTH } into mpmr
select mpmr.ToList();
Use Linqpad and recreate the linq (even by bringing in your assemblies) in a C# query. Run the query. Then in the output, there is a selection button of SQL which will show the sql code.
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
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 have a problem with one of my queries using linq 2 entites. I'm trying to view the query before it is generated to the db but without any success. I tried using ToTraceString() but couldn't cause the query could not be cast to ObjectQuery.
this is my query:
var movies = (from m in watchedRepo.GetAll().Where(c => c.iUserId == userId).ToList()
join f in moviePageViewsRepository.GetAll() on m.iMovieId equals f.iMovieId
group f by new JoinClass { MovieId = f.iMovieId, Points = m.iPoints }
into g
orderby g.Key.Points descending , g.Sum(d => d.iScore) descending
select new JoinClass { MovieId = g.Key.MovieId, Points = g.Key.Points, PageViews = g.Sum(d => d.iScore) }).Skip(skip).Take(take);
if I try to execute it from linq I get an out of memory exception.
any ideas please?
The problem is with your ToList() in the first line of your query. This will immediately fetch all rows from wachtedRepo with the specified UserId.
Because your query will then become a hybrid Linq to Entities / Linq to Objects, you can't cast to an ObjectQuery. Is your query still working when you remove ToList()?
If you want to see what's really happening in your Sql Server, I would suggest using the Sql Server Profiler tools to view your queries.
Assuming watchedRepo is the Linq to SQL object representing the database connection
watchedRepo.Log = Console.Error;
All SQL queries will be printed to standard error.