1

I want to know all the Select Statement that is used to retrieve the data of one particular table from the database. I have used .First and .FirstOrDefault it gives me the desired result but when i use .Last it throws me an error.My feeling is that .First gives us the first row of the table so why error in .Last and why we use .FirstOrDefault because .First will surely give us First row so why to use .FirstOrDefault and what is the default value of it as it is used to be away from the any exception and please let me know the other functions as well to retrieve the data from the table. I have used

var val=db.AccountBank .First();//gives me the Result
var val1=db.AccountBank .Last();//gives me the following error

LINQ to Entities does not recognize the method 'Invoice.AccountBank LastAccountBank' method, and this method cannot be translated into a store expression.

1 Answer 1

1

You have to use orderby decending and Take(1) because Linq can not translate the Last() to any valid sql statment.

AccountBank.OrderByDescending().Take(1).SingleOrDefault();
Sign up to request clarification or add additional context in comments.

5 Comments

but why??I can even do it by AccountBank.ToList().Last(); as well
and i need others function as well
When you use ToList().Last() the records are fetched from the database and then the last one is selected. If you do First or FirstOrDefault the query will use TOP 1 to retreive the record.
yes but to retreive it fetched from the database only right??so why not in case of .Last() in my feeling it .First() it must fetch the First row and in .Last() it must fetch Last row from the table
Unfortunately LINQ to SQL doesn't work that way. As Nilesh said, using .ToList().Last "caches" the data into a list, then chooses the last one from that. This may or may not solve your problem, especially if you are using a large set of data. You will just need to think out what functions you need and find out if LINQ is capable of doing them. If not, you'll just have to hack something together.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.