109221793
109221793

Reputation: 16897

Select most recent entry from database using LINQ to Entities

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.

Upvotes: 2

Views: 1340

Answers (2)

RichardW1001
RichardW1001

Reputation: 1985

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;

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

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

Upvotes: 1

Related Questions