Rule Definition
A query that retrieves all columns of a table can potentially be the source of important changeability problems. One cannot control how the columns will be ordered and returned to the client. This can lead to important data inconsistencies and thus stability issues.
Also performance problems may arise when the execution of the query returns a large result sets (many row with all the columns may then become a huge amount of data to transport over the network). Thus optimizer module can't provide a correct execution.
Remediation
Review the design of the query to select only useful columns.
For EF, this is achieved thanks to a LINQ Select clause: by using eager loading with the Include method, we reduce the number of database roundtrips, resulting in a significant improvement in query execution time.
Violation Code Sample
using System.Linq;
using YourDbContextNamespace;
public class YourProgramClass
{
public static void Main(string[] args)
{
using (var context = new YourDbContextClass())
{
foreach (var blog in context.Blogs) // ⚠️ VIOLATION : Retrieve all columns of all blogs
Console.WriteLine("Blog: " + blog.Url);
}
}
}
}
sample 2
var customer =
(from cust in dataContext.Customers // ⚠️ VIOLATION : all columns are retrieved
select cust).ToList();
Fixed Code Sample
using System.Linq;
using YourDbContextNamespace;
public class YourProgramClass
{
public static void Main(string[] args)
{
using (var context = new YourDbContextClass())
{
foreach (var url in context.Blogs.Select(b => b.Url)) // ✓ FIXED: Retrieve only the Url column
{
Console.WriteLine("Blog URL: " + url);
}
}
}
}
sample 2
var customer =
(from cust in dataContext.Customers
select new { // ✓ FIXED : only 3 named columns are retrieved
customer. CustomerID,
customer.Name,
customer.Address
}). ToList ();
Reference
Microsft Entity Framework - Efficient Querying - Project only properties you need
https://learn.microsoft.com/en-us/ef/core/performance/efficient-querying#project-only-properties-you-need
Optimizing database performance in Entity Framework
https://www.site24x7.com/learn/optimize-entity-framework-performance.html
Related Technologies
Technical Criterion
Efficiency - SQL and Data Handling Performance
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.