0

How can I get the first record in a table independent of the rows primary key?

I'm using MVC 4, with EF Code First and a database context, or will I have to use LINQ for this?

I think I can use db.ToList() to get the list and then loop through the specific elements, but wouldn't that "download" the whole table?

Cause if it does Isn't it bad practice and inefficient?

EDIT: Meant to say "first record", sorry for any confusion :)

Graknol
  • 55
  • 1
  • 8
  • 6
    There is no concept of 'first row' without an order. If you select records from a table, there is no guarantee they will come back in any particular order without an ORDER BY clause. To get the first record from the database in LINQ you use .Take(1). Without an Order by there is no way to predict what this row is. See here: http://stackoverflow.com/questions/192203/whats-the-linq-to-sql-equivalent-to-top – Nick.Mc Nov 21 '12 at 07:11
  • Why do you want to do this? What are you trying to achive. I cant think of a reason to just want the first row without 'first' being in some context - eg first row inserted... – Judo Nov 21 '12 at 10:42

1 Answers1

2

Have you tried:

db.List.First();
  • If you don't have order by clause the rows will be ordered according to clustered index (primary key by default)
  • If you have order by clause rows will be ordered by your specified order
testCoder
  • 7,155
  • 13
  • 56
  • 75
  • 1
    If you don't have `ORDER BY`, the server is free to return the rows in *any* order it finds convenient. It is by no means guaranteed that this will follow the clustered index order. – Damien_The_Unbeliever Nov 21 '12 at 08:06
  • Not sure if EF uses `top` or not, but MSDN: http://msdn.microsoft.com/en-us/library/ms189463.aspx "When TOP is used in conjunction with the ORDER BY clause, the result set is limited to the first N number of ordered rows; otherwise, it returns the first N number of rows in an *undefined* order." (emphasis my own). -1, just because this is **not** the answer (the answer being is that there *isn't* a first row). – JayC Nov 21 '12 at 17:21
  • Actually, I'll grant, for all I know EF may do something behind the scenes that might give an actual ordering.. let me revoke my -1 until I know for sure it doesn't (which, honestly, might be a while). – JayC Nov 21 '12 at 17:25