C
C#7d ago
reeeeeee

Where to handle mapping between DTOs and Entity objects?

Lets say I have controller GET /users/ which returns UserDTO. Where would I do this mapping between User and UserDTO? - In controller: userService.GetUsers -> transform to UserDTO list -> return list - in service: Method UserService.GetUsers does the mapping and returns UserDTO list - in separate service: I have two methods in my service: GetUsers (which returns Entity objects) and GetUsersDTO (which calls GetUsers method and map it) - anything else?
3 Replies
Unknown User
Unknown User7d ago
Message Not Public
Sign In & Join Server To View
sibber
sibber7d ago
yeah id make it an extension method, and probably in its own class that handles mapping it depends on the arch
Kauan
Kauan6d ago
You could do the projection in the database side and already return the response/dto from your service
public async Task<ErrorOr<UserResponse>> Handle(
GetCurrentUserQuery query,
CancellationToken cancellationToken)
{
var user = await _context.Users
.AsNoTracking()
.Where(u => u.Id == _userContext.UserId)
.Select(u => new UserResponse
{
Id = u.Id,
Email = u.Email,
FirstName = u.FirstName,
LastName = u.LastName,
FullName = u.FullName,
ImageUrl = u.ImageUrl,
})
.FirstOrDefaultAsync(cancellationToken);

if (user is null)
{
return UserErrors.NotFound;
}

return user;
}
public async Task<ErrorOr<UserResponse>> Handle(
GetCurrentUserQuery query,
CancellationToken cancellationToken)
{
var user = await _context.Users
.AsNoTracking()
.Where(u => u.Id == _userContext.UserId)
.Select(u => new UserResponse
{
Id = u.Id,
Email = u.Email,
FirstName = u.FirstName,
LastName = u.LastName,
FullName = u.FullName,
ImageUrl = u.ImageUrl,
})
.FirstOrDefaultAsync(cancellationToken);

if (user is null)
{
return UserErrors.NotFound;
}

return user;
}

Did you find this page helpful?