CRITICAL
Rule Definition
Calling SaveChanges() inside a loop causes multiple database transactions, each incurring:
- Higher latency and I/O overhead
- Increased risk of partial updates
- Degraded performance at scale
Remediation
To address this issue, consider the following remediation steps:
- Move the context call outside the loop if the operation does not depend on loop variables.
- If the operation is required within the loop, optimize the code to minimize the number of context calls by fetching the required data in bulk or using caching mechanisms.
- Use appropriate error handling and transaction management to handle exceptions or errors that may occur during context calls within the loop.
Violation Code Sample
foreach (var item in items)
{
// Do something with the Context
dbContext.SaveChanges(); // ⚠️ VIOLATON : called in every iteration
}
Fixed Code Sample
foreach (var item in items)
{
// Do something with the Context
}
dbContext.SaveChanges(); // ✓ FIXED: one batch save
Reference
https://learn.microsoft.com/en-us/ef/core/saving/basic
CWE-1050: Excessive Platform Resource Consumption within a Loop
https://cwe.mitre.org/data/definitions/1050.html
OMG ASCPEM ASCPEM-PRF-8
https://www.omg.org/spec/ASCPEM/1.0/PDF page 31
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.