Projection (EF Core)
ℹ️ Description: Use ProjectTo() with Entity Framework to translate mappings to SQL for better performance.
Code Example
// Instead of this (inefficient):
var users = dbContext.Users.ToList();
var userDTOs = _mapper.Map>(users);
// Do this (efficient):
var userDTOs = dbContext.Users
.ProjectTo(_mapper.ConfigurationProvider)
.ToList();
⚡ Why ProjectTo is Important
Without ProjectTo (Inefficient)
// Retrieves ALL columns from User table
var users = await dbContext.Users.ToListAsync();
// Maps in memory (after loading all data)
var userDTOs = _mapper.Map<List<UserDTO>>(users);
With ProjectTo (Efficient)
// ProjectTo translates mapping to SQL
// Only retrieves columns needed for UserDTO
var userDTOs = await dbContext.Users
.ProjectTo<UserDTO>(_mapper.ConfigurationProvider)
.ToListAsync();
Performance Comparison
| Approach | Data Transferred | Memory Usage | Performance |
|---|---|---|---|
| Without ProjectTo | All 20 columns | High | ❌ Slower |
| With ProjectTo | Only 5 needed columns | Low | ✅ Faster |
Best Practice: Always use ProjectTo when working with Entity Framework Core and IQueryable for better performance!