Description
in "Encapsulating data" section at https://learn.microsoft.com/en-us/dotnet/architecture/modern-web-apps-azure/work-with-data-in-asp-net-core-apps#encapsulating-data the code sample is inefficient since the update case would require TWO scans of the Items collection, so IMHO better to code the
var existingItem = Items.FirstOrDefault(i => i.CatalogItemId == catalogItemId);
and then test that nullable object
if(existingItem==null){_items.Add(new BasketItem{..}} else existingItem.Quantity+=quantity;
so eliminating 2nd scan, the Any() and the return statement.
Example used here of in-memory database perhaps not too bad, but devs should realise that multiple scans of a real remote relational db could incur 2 roundtrips. doh!
Actually I also quarrel with using the public Items wrapper rather than the private underlying _items List
surely this code should manipulate its private List to avoid List BCL having to brew-up a wrapper [again]?
Document Details
⚠ Do not edit this section. It is required for learn.microsoft.com ➟ GitHub issue linking.
- ID: 8e1a443c-c3dd-b865-58b2-0ff0902308ce
- Version Independent ID: d974261f-2544-dee9-f401-e02d715012cb
- Content: Work with data in ASP.NET Core Apps
- Content Source: docs/architecture/modern-web-apps-azure/work-with-data-in-asp-net-core-apps.md
- Product: dotnet-architecture
- Technology: modern-web-apps-azure
- GitHub Login: @ardalis
- Microsoft Alias: wiwagn