Select most recent entry from database using LINQ to Entities - c#

I need to select the most recent date from my database table and store it in a variable.
I'm not very familiar with linq to entities but I gave it a go myself however I only got so far.
This is how far I got:
IQueryable<DateTime> date = from ftp in ctn.FTPRuns
orderby ftp.LastRun descending
select ftp.LastRun;
Can anyone tell me how I can modify this query to just select the most recent entry. I have tried "select ftp.LastRun.First();" however this is not an option in intellisense for me.
any help would be appreciated.
thanks.

The result of what you have there (date) is an ordered IQueryable. You can just call date.First() to get the first one in that sequence.
Otherwise if you want to cut a step, wrap your query in brackets and call.First on it to just get the date.
DateTime date = (from ftp in ctn.FTPRuns
orderby ftp.LastRun descending
select ftp.LastRun).First();
You could otherwise use lambdas:
DateTime date = ctn.FTPRuns.OrderByDescending(f => f.LastRun).First().LastRun;

IQueryable<DateTime> dates = from ftp in ctn.FTPRuns
orderby ftp.LastRun descending
select ftp.LastRun;
DateTime date = dates.First();

Related

Linq DateTime Operations Comparison

So I have this statement
SearchResults = (from s in dbContext.tbl_ShippingProgram
where s.eta_date.Date > DateTime.Now.Date.AddMonths(-TimePeriod.Value)
select s).ToList();
Where SearchResults is defined as
public List<tbl_ShippingProgram> SearchResults { get; set; }
And where TimePeriod.Value is a int
I'm having difficulties figuring out why this doesn't work, there's nothing wrong the with just selecting all values since
SearchResults = (from s in dbContext.tbl_ShippingProgram
select s).ToList();
Works perfectly fine. Any and all help is appreciated <3
EDIT
- The issue is that it's not returning anything where it definately should be, checked the values in the db and the calculated DateTime.Now value and it should be returning something
Try DateTime.Now.AddMonths(-TimePeriod.Value).Date
I think you want the date portion of the datetime after the adjustment. This trips me up all the time too...
Couple of other things to try if this doesn't help:
Calculate the date outside of your linq statement (although you're not getting an unsupported error, but still).
Try using .Compare() for datetimes.
Do some sanity checking by using a hard-coded date that clearly encompass all results.

Displaying only free time slots which haven't been booked for any date

The following query displays all free time slots for a specific which haven't been booked:-
SELECT DISTINCT tbl_available.timeslot
FROM tbl_appointment RIGHT JOIN
tbl_available ON (tbl_appointment.employeeID = tbl_available.employeeID) AND (tbl_appointment.apptTime = tbl_available.timeslot)
WHERE tbl_appointment.apptTime IS NULL
ORDER BY 1;
This is fine but I'm trying to get it so that it runs this query based on any date which is passed in as a parameter using c#. (I only need help with the SQL side of things)
Using the following tables:-
Appointment:- Availability:-
apptTime timeSlot
apptDate DoctorId
patientID
Any suggestions would be greatly appreciated.
AND apptDate = thepassedindate

Retrieve only the first row from a table in Entity Framework

Background:
Entity Framework 4, with SQL Server 2008
Problem:
I have a table Order. Each row has a column Timestamp.
The user can choose some time in past and I need to get the Order closest to the specified time, but that had occurred before the specified time. In other words, the last order before the specified time.
For example, if I have orders
2008-01-12
2009-04-17
2009-09-24
2010-11-02
2010-12-01
2011-05-16
and choose a date 2010-07-22, I should get the 2009-09-24 order, because that's the last order before the specified date.
var query = (from oData in db.OrderDatas
where oData.Timestamp <= userTime
orderby oData.Timestamp ascending
select oData).Last();
This is closest to what I am trying. However, I am not sure how exactly does the Last operator work when translated to SQL, if it's translated at all.
Question:
Will this query fetch all data (earlier than userTime) and then take the last element, or will it be translated so that only one element will be returned from the database? My table can hold very large number of rows (100000+) so performance is an issue here.
Also, how would one retrieve the closest time in the database (not necessarily the earlier time)? In the example of 2010-07-22, one would get 2010-11-02, because it is closer to the date specified than 2009-09-24.
In general, if you're concerned about how LINQ behaves, you should check what does happen with the SQL. If you haven't worked out how to see how your LINQ queries are turned into SQL, that should be the very next thing you do.
As you noted in your comment, Last() isn't supported by LINQ to SQL so the same may be true for EF. Fortunately, it's easy to use First() instead:
var query = (from oData in db.OrderDatas
where oData.Timestamp <= userTime
orderby oData.Timestamp descending
select oData).First();
Try using:
var query = (from oData in db.OrderDatas
where oData.Timestamp <= userTime
orderby oData.Timestamp descending
select oData).Take(1);
It's the equivalent of TOP 1
Question:
Will this query fetch all data (earlier than userTime) and then take
the last element, or will it be translated so that only one element
will be returned from the database? My table can hold very large
number of rows (100000+) so performance is an issue here.
In this case, using the first() approach, the query will be executed immediately and it will optimized in such a way that it will ony retrieve 1 record. Most probably a top(1) select. You really need to check the genereated sql with a sql profilihg tool or by using the log of the datacontext. Or you can use linqpad. linq-2-sql can lead to N+1 queries if not used the proper way. This behaviour is quite predictable but in the beginning you really have to be aware.

linq query with time zones groupby

I have a linq-to-sql query that works by grouping the data it retrieve in days for a particular month:
var Output = from c ....
where .... // this is the month parameter
group c by c.TheTime.Date into daygroups
select new MyModel(){
Prop1 = (from x in daygroups
where....
select x.ID).Count()
}.ToList();
The problem is that this groups by datetime in terms of server time. I'd like to group them by interval of times so that if we're looking at the result with California time, we're really looking at a list of days that starts at midnight PST.
The query returns a count. The solution I've figured out for now would be to return all the raw data between the beginning and the end of the month in a certain timezone, and then rearranging the raw data in days with the correct timezone, and only then do the count.
Is there a better way to do this?
Try grouping by c.TheTime.Date.AddHours(-8).
However, I'm not sure whether that will work correctly.

Ordering nullable DateTime in Linq to SQL

I have started using Linq to SQL for a project im working on and i have run into a problem when ordering by a DateTime field but since the DateTime allows nulls the nulls are coming up as less than the actual dates in there.
So i pretty much want the ones with a date to be at the top (ordered either way) then all the ones with no date set.
jobList = from ju in context.Job_Users_Assigned
where ju.UserID == user.ID
select ju.Job;
return jobList.OrderByDescending(j => j.EndDate);
This is a bit of a hack, but it appears to work with Linq to SQL:
return from ju in context.Job_Users_Assigned
where ju.UserID == user.ID
orderby ju.Created ?? DateTime.MaxValue descending;
So I'm substituting the maximum possible DateTime value when the actual "Create" value is null. That'll put all the null values at the top.
Another approach is to order by whether the date field has a value. This works too:
return from ju in context.Job_Users_Assigned
where ju.UserID == user.ID
orderby ju.Created.HasValue descending
orderby ju.Created descending;

Categories