2

My process to get first N rows

  1. Get All Data from Database using Entity Framework

    var list = new MyDbContext().Set<EntityName>();

  2. Get First N rows using C#

    var firstNRows = list.Take(N); // N = int

Suppose,

If N = 2 then I want the first 2 rows of the table but entity give me all rows of the table. Is there any way that entity give me only first N rows from the table not all data from the table?

2 Answers 2

3

Actually var list = new MyDbContext().Set<EntityName>(); gets no data at all, it returns a IQueryable<EntityName> which is just a representation of a query of all rows.

When you do var firstNRows = list.Take(N); that also gets no data, that also is a IQueryable<EntityName> which is a representation of a query of the first N rows in the database.

You don't actually get data from the database until you do something like a .ToList()

var firstNRowsList = firstNRows.ToList(); //The database is queried here for the first time.
Sign up to request clarification or add additional context in comments.

1 Comment

In other words using ToList or other methods that forces the enumeration will load records in memory and Take(N) will only return some records but others will not be used. So instead you should use Take(N) on the interface IQuerable<T> before enumeration. csharp // will fetch only 15 records in memory var awards = _context.Awards.AsNoTracking().Take(15).ToList() // will fetch all records in memory and then give you 15 var badQueryAwards = _context.Awards.AsNoTracking().ToList().Take(15);
1
var awards = await _context.Awards.AsNoTracking()
    .OrderBy(x => x.Id)
    .Take(15)
    .ToListAsync();

2 Comments

As you have added AsNoTracking, please motivated why.
@Dejan for better performance. The code only fetches the data and returns without modifying it, so there is no reason for EF Core to track it. Using AsNoTracking will improve the performance and there is no reason not to use it. Also using AsNoTracking is good because maybe in the future you'll need to fetch not 15 record but 100'000 and then the performance impact is significant.

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.