Search code examples
c#-4.0lambdalinq-to-entities

Linq to entities get first or last from 2million rows


I'm learning LINQ to Entities in C# .NET4.0 Winforms.

I have a MSSQL database table with over 2million rows, eventually more and I need to just pull back the first record or the last record in the database.

I tried getting the last record but it doesn't seem to want to work for me :( It builds okay, but during RunTime I get a

LINQ to Entities does not recognize the method 'StockTraderRobotDT.IntradayFuturesTick       
Last[IntradayFuturesTick](System.Linq.IQueryable`1[StockTraderRobotDT.IntradayFuturesTick])' 
method, and this method cannot be translated into a store expression.            

I'm doing this...

using (DataFeedEntities db = new DataFeedEntities())
{
   IntradayFuturesTick tick = db.IntradayFuturesTicks.Last();
}

I know it's probably an easy answer but I'm still getting my head around LINQ.

Thanks for your help.

David


Solution

  • You need to sort the results in descending order then use the Take extension method.

    using (DataFeedEntities db = new DataFeedEntities())
    {
        IntradayFuturesTick tick = db.IntradayFuturesTicks
           .OrderByDescending(x => x.Id)
           .Take(1)
           .Single();
    }
    

    You could also use First instead of Take, but I'm not sure if that will return only a single result in the database query.