Avoid Materialization in Entity Framework with IQueryable

𝐈𝐬 𝐲𝐨𝐮𝐫 𝐀𝐏𝐈 𝐬𝐥𝐨𝐰𝐞𝐫 𝐭𝐡𝐚𝐧 𝐢𝐭 𝐬𝐡𝐨𝐮𝐥𝐝 𝐛𝐞? 𝐓𝐡𝐞 𝐫𝐞𝐚𝐬𝐨𝐧 𝐦𝐢𝐠𝐡𝐭 𝐛𝐞 𝐚 𝐬𝐢𝐧𝐠𝐥𝐞 𝐥𝐢𝐧𝐞 𝐨𝐟 𝐜𝐨𝐝𝐞. In Entity Framework, there is a big difference between building a query and running one. When you use IQueryable, you are just writing instructions. Nothing happens in the database yet. The danger starts when you call .𝑻𝒐𝑳𝒊𝒔𝒕(). This is called "Materialization." It tells your application to stop building the query, go to the database, and pull all that data into your server’s memory. 𝐓𝐡𝐞 𝐰𝐫𝐨𝐧𝐠 𝐰𝐚𝐲: var data = context.Users.ToList().Where(u => u.IsActive); In this case, you fetch every single user from the database first. The filtering happens in your app's RAM. If you have 100,000 users, your app will struggle. 𝐓𝐡𝐞 𝐫𝐢𝐠𝐡𝐭 𝐰𝐚𝐲: var data = context.Users.Where(u => u.IsActive).ToList(); By placing the filter before the list command, EF Core sends a smart SQL query to the database. You only download the users you actually need. 𝐓𝐡𝐞 𝐫𝐮𝐥𝐞 𝐢𝐬 𝐬𝐢𝐦𝐩𝐥𝐞: Use IQueryable to filter, sort, and join. Use .𝑻𝒐𝑳𝒊𝒔𝒕() only when you are ready to use the final results. Build your query fully before you execute it. Your database and your users will thank you. #DotNet #EFCore #EntityFramework #SoftwareEngineering #CleanCode #ProgrammingTips

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories