I am building an API which, amongst other things, needs to handle users. I am building it with C# 10 and .NET 6. In order to receive/return data in the API end points, I am using records. So for example, this could be an end point which returns all users:
[HttpGet]
public IActionsResult ListUsers()
{
// The '.AsDto' method extracts the relevant information
// from the domain model 'User' in the form of a record (dto).
List<UserDto> users = _userRepo.GetAll().AsDto();
return Ok()
}
public record UserDto(string Username, string FirstName, string LastName);
This works just fine and should be (I think) reasonably understandable. However, the UserRepository is using EntityFrameworkCore, to communicate with the database. So let's look at something like an AddUser() method on the repository:
internal void AddUser(UserModel user)
{
// The 'Validate' method validates the input and returns
// the data in a EF Core friendly record (see below).
UserDto userDto = Validate(user);
_dbContext.Users.Add(userDto);
}
// This looks similar to the previous dto, but notice there also is an ID
public record UserDto(Guid Id, string UserName, string FirstName, string Lastname);
Now, suddenly, I have two almost identical DTO's/records. I could make them identical. This would solve the naming problem, but it doesn't feel right. After all, they serve different purposes.
I could also name them slightly differently like UserApiDto and UserContextDto, but this seems like a potential booby trap for future work with two so similar items.
This seems like a problem which other people should have encountered. Is there a best practice in regards to handling this "double dto" issue, when building API's with EF Core?