Friday, November 05, 2010

SELECT TOP (n) in Entity Framework or LINQ to SQL

I have recently inherited a project that makes use of WCF Data Services with the Entity Framework being used as the ORM to facilitate this with Microsoft SQL Server 2008 R2.

I had a requirement to only ever retrieve a maximum of 100 items no matter the query. In SQL this is easy and can be achieved using the SELECT TOP (N).. syntax.

Using a lambda expression to return a collection of IQueryable objects can be achieved simply as the following:
IQueryable<MyObject> resultSet =
service.MyObjects.Where(c => c.Name.Contains(searchText))
.OrderBy(x => x.Name)
Remember here that the actual REST call is not made until you call ToList() on the collection. This query simply creates the REST URL as a string.

But using the extension method Take(n) will translate to TOP in SQL.


Anonymous said...

Thank you Simon

John Poblete

Francisco Silva said...

Tanks friend!!