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."

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?
Who is Participating?
Fernando SotoConnect With a Mentor RetiredCommented:
Hi dynamk;

In answer to your question, "Can someone explain to me why the following statement:
   var record = _efEntities.Records.LastOrDefault();
   Throws this error:"

The reason why the above statement throws an error is that not all Linq operators are supported in LINQ to Entities queries, please see this link documenting this,

To the second half of the question, "But I am able to use:
    var record = _efEntities.Records.ToList().LastOrDefault();"

This statement, var record = _efEntities.Records.LastOrDefault();, instructs the Entity Framework to construct a T-SQL query using the unsupported operator LastOrDefault(). While this statement,  var record = _efEntities.Records.ToList().LastOrDefault();, uses _efEntities.Records to build the T-SQL then the returned result is exported to a generic List and then the LastOrDefault() is applied to the List object. Therefore the LastOrDefault() is not used in the T-SQL query on the results of that query.

I hope that answers your question.

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.
dynamkAuthor Commented:
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.
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

I had this issue as well with different collections, so I sorted out by using Lambda Expression. Try out Lambda Expressions for a try!
dynamkAuthor Commented:
Clear and concise. Thank you.
Fernando SotoRetiredCommented:
Not a problem, glad I was able to help.  ;=)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.