C# — DTO (Data Transfer Object)
Published in
1 min readMay 19, 2024
DTO is a method provide an efficient way to Hide specific properties that clients don’t need to receive
Example 👨💻
1- Suppose we have Users’ information stored in a database and is represented a class Calling User.
2 -However, we don’t want to return all this information to the client. We wants to return just the user’s first name, last name, and email address.
3- The DTO class can then be used in your API controller to return the necessary information.
// 1-
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
}
// 2-
public class UserDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
// 3-
[HttpGet("api/users/{id}")]
public IActionResult GetUser(int id)
{
var user = database.Users.SingleOrDefault(user => user.Id == id);
if (user == null)
{
return NotFound();
}
var userDto = new UserDto
{
FirstName = user.FirstName,
LastName = user.LastName,
Email = user.Email
};
return Ok(userDto);
}