adsense

Sunday, March 30, 2025

Entity Framework Selectmany

 In Entity Framework Core, the SelectMany operation flattens collections, which can lead to unexpected results if not carefully applied. For example, in a query that filters students and their active courses:

var activeCourses = await _employeeRepository

    .GetAllEmployees()

    .Where(employee=> employee.IsActive)

    .SelectMany(employee=> employee.PayeDetails)

    .Where(payDetail=> payDetail.IsTermnated)

    .ToListAsync();

The Where clause before SelectMany filters the employees, but after SelectMany, the query works with a flattened collection of pay details. This means the second Where clause filters the pay details, not the employees. As a result, you might get pay details from terminated employees because the filtering is done on the flattened collection of pay details, not the original employee collection. 

In some cases Selectmany can act like a CrossJoin as well.


Cheers

Samitha

Saturday, March 1, 2025

Ef .Net Core DbSet.ExecuteUpdate

 EF Core 7.0 introduces the ExecuteUpdate method, which allows for updating entities in the database based on a query result. However, it requires explicit specification of the changes to be made, as EF Core does not automatically detect them. Tracked entities will not remain in sync, and additional commands may need to be issued in a specific order to avoid violating database constraints (e.g., updating dependents before deleting a principal).

The ExecuteUpdate method complements, rather than replaces, the existing SaveChanges mechanism. It functions similarly to the ExecuteDelete method, but with the key difference that an update requires specifying which properties to update and how to do so, typically using calls to SetProperty.


Cheers.

Samitha