Muhammad Waseem Profile picture
Senior Software Engineer (.NET) | Tweets and threads are related to C# and .NET

Mar 12, 2023, 8 tweets

๐Ÿ’ก 7 Tips to write better LINQ Queries

๐”๐ฌ๐ž ๐จ๐Ÿ ๐€๐ฌ๐๐จ๐“๐ซ๐š๐œ๐ค๐ข๐ง๐  : 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. #dotnet

See thread ๐Ÿงต๐Ÿ”ฝ

๐ˆ๐ง๐œ๐ฅ๐ฎ๐๐ž ๐ง๐ž๐œ๐ž๐ฌ๐ฌ๐š๐ซ๐ฒ ๐„๐ง๐ญ๐ข๐ญ๐ข๐ž๐ฌ ๐š๐ง๐ ๐‚๐จ๐ฅ๐ฎ๐ฆ๐ง๐ฌ : While retrieving data from multiple table make sure to include only necessary tables and columns Use eager loading only when it is necessary.
#dotnet

๐…๐จ๐ซ ๐ฅ๐š๐ซ๐ ๐ž ๐๐š๐ญ๐š ๐ฎ๐ฌ๐ž ๐’๐ค๐ข๐ฉ ๐š๐ง๐ ๐“๐š๐ค๐ž : Use skip and take to retrieve data from table for large collections because if we try to bring all data in single try it can take time that will give bad user experience takes next values.
#dotnet

๐”๐ฌ๐ž ๐š๐ฌ๐ฒ๐ง๐œ ๐ฆ๐ž๐ญ๐ก๐จ๐๐ฌ : For better user experience use async methods e.g. FirstOrDefaultAsync , SingleOrDefaultAsync and ToListAsync.
#dotnet

๐‘๐ž๐๐ฎ๐œ๐ž ๐“๐ซ๐ข๐ฉ๐ฌ ๐ญ๐จ ๐ƒ๐š๐ญ๐š๐›๐š๐ฌ๐ž : 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.
#dotnet

๐”๐ฌ๐ž ๐“๐ซ๐ฒ๐†๐ž๐ญ๐๐จ๐ง๐„๐ง๐ฎ๐ฆ๐ž๐ซ๐š๐ญ๐ž๐๐‚๐จ๐ฎ๐ง๐ญ : For large of data we use pagination and it is displayed on basis of total records. Use TryGetNonEnumeratedCount instead of count it attempts to determine the number of elements in a sequence without forcing an enumeration

๐”๐ฌ๐ž ๐ˆ๐๐ฎ๐ž๐ซ๐ฒ๐š๐›๐ฅ๐ž : For long and condition based filters use IQueryable,it executes queries on the server side.After all conditions we can use ToList to fetch data it makes query faster as we are first creating complete query and then we are bringing the data
#dotnet

๐Ÿ“ง If you like it join family of 550+ Software Engineers via my Newsletter : lnkd.in/dNHxJGRG

#dotnet

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling