EP 2 : Tips to write better LINQ Queries

Use of AsNoTracking

For read only queries e.g. (GetAll,GetById etc.) use AsNoTracking , when we use it entities are not tracked for change so it brings data more speedily.

Include necessary Entities and Columns

While retrieving data from multiple table make sure to include only necessary tables if you add tables that are not needed it will increase headache of query.

Use eager loading only when it is necessary.

Similarly don’t select the all columns from table , just retrieve necessary columns information using SELECT

For large data use Skip and Take

When you are dealing with a lot of information use Skip and Take to retrieve data from table because if we try to bring all data in single try it can take time which will give a bad user experience, Skip and Take two integer and skips provided values and then takes next values.

Use async methods

For better user experience use async methods e.g. FirstOrDefaultAsync , SingleOrDefaultAsync and ToListAsync

Reduce Trips to Database

Use bulk operations available for SAVE/DELETE operations instead of iterating one by one it will reduce trips to database. After that only write one line await _context.SaveChangesAsync(); to reflect changes over database.

Use TryGetNonEnumeratedCount

While working with large collection of data we use pagination and our pagination is displayed on the basis of total records available. So instead of .Count() method use TryGetNonEnumeratedCount it attempts to determine the number of elements in a sequence without forcing an enumeration.

Use of IQueryable

When you are dealing with a long list of filters and your filters are condition based make use of IQueryable ,it executes queries on the server side.

After all conditions, we can use .ToList() to fetch data, so it makes the query faster because we are first creating a complete query and then we are bringing the data.

There are 3 ways you can help me in growing:

  1. Subscribe to my YouTube Channel

  2. Subscribe to my Weekly .NET Newsletter of C#/.NET

  3. Download my eBook at Gum Road which contains 30+ .NET Tips