DAO vs DTO

DAO vs DTO

DTO (Data Transfer Object) and DAO (Data Access Object) are both design patterns used in software engineering, but they serve different purposes.

DTO is used to transfer data between layers of an application or between different applications. It is a simple object that contains data and has no behavior. The primary purpose of DTO is to reduce the amount of data that needs to be transferred over a network or between different layers of an application. A simple example of DTO would be a class that represents a user’s information, such as their name, email address, and phone number. This information can be transferred between layers or different applications without the need for additional processing.

DAO, on the other hand, is used to abstract the details of data persistence from the rest of the application. It provides a simple interface for accessing data stored in a database or other data storage system. DAO typically contains methods for creating, retrieving, updating, and deleting data from the data storage system. A simple example of DAO would be a class that provides methods for retrieving user information from a database. The class would hide the details of how the data is stored and retrieved from the database, allowing the rest of the application to access the data using a simple interface.

To summarize, DTO is used for transferring data between layers or applications, while DAO is used for abstracting the details of data persistence from the rest of the application.

// DTO example
public class UserDTO
{
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}

// DAO example
public class UserRepository
{
private readonly DbContext _dbContext;

public UserRepository(DbContext dbContext)
{
_dbContext = dbContext;
}

public void AddUser(UserDTO userDTO)
{
var user = new User
{
Name = userDTO.Name,
Email = userDTO.Email,
Phone = userDTO.Phone
};
_dbContext.Users.Add(user);
_dbContext.SaveChanges();
}

public UserDTO GetUser(int id)
{
var user = _dbContext.Users.Find(id);
if (user == null)
return null;

var userDTO = new UserDTO
{
Name = user.Name,
Email = user.Email,
Phone = user.Phone
};
return userDTO;
}
}