Link to home
Start Free TrialLog in
Avatar of dynamk
dynamk

asked on

Linq to Entities syntax

Can someone explain to me why the following statement:
   var record = _efEntities.Records.LastOrDefault();
Throws this error:
    System.NotSupportedException was unhandled
  Message="LINQ to Entities does not recognize the method 'EFSchedulerDemo.Resource Last[Resource](System.Linq.IQueryable`1[EFSchedulerDemo.Resource])' method, and this method cannot be translated into a store expression."
  Source="System.Data.Entity"

But I am able to use:
    var record = _efEntities.Records.ToList().LastOrDefault();

How can I get the first or last record without having to call ToList() every time if possible?
Avatar of himanshut
himanshut
Flag of Australia image

Use a foreach to traverse the List of records and take the value where i=0, i<List.count-1

Hope that should give you the Last and first record out of the List.
Avatar of dynamk
dynamk

ASKER

What I am trying to find out is how to get the entity object Without using the List. The List already works fine but I don't understand why I cannot just use var record =_efEntities.Records.LastOrDefault() without getting an error.
I had this issue as well with different collections, so I sorted out by using Lambda Expression. Try out Lambda Expressions for a try!
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dynamk

ASKER

Clear and concise. Thank you.
Not a problem, glad I was able to help.  ;=)