Benji
Benji

Reputation: 509

Usage of entities and DTOs when performing read and create/update on a database

What is the proper usage of entities and DTOs when performing database actions? My mindset is that it seems best to use DTOs when reading from a database and entities when creating/updating to a database. As a small example let's consider teh following:

Book Class

public class Book/Entity
{
  public int Id {get; set;}
  public string Title {get; set;}

  public int AuthorId {get; set;}
  public Author Author {get; set;}

}

Author Class/Entity

public class Author
{
  public int Id {get; set;}    
  public string Name {get; set;}

  public int BookId {get; set;}
  public Book Book {get; set;}
}

BookAuthorDto Class

public class BookAuthorDto
{
  public string Title {get; set;}    
  public string Name {get; set;}
}

Now, let's say we have a WebApi Book controller.

public class BookController : ApiController
{
  public IHttpActionResult GetBook(int id)
    {
        var BADto = context.Book.Where(book => book.ID == id)
            .Select(book => new BookAuthorDto
            {
                Title = book.Title,
                Name = book.Author.Name
            });

        return Ok<BookAuthorDto>(BADto);
    }

  public IHttpActionResult PostBookEntity(Book book)
  {
      // Code for saving book to DB
  }

  public IHttpActionResult PostBookDto(BookAuthorDto BADto)
  {
      // Code for creating entities from DTO
      // Code for saving the created entities to Database
  }
}

Which method is considered more "proper" the PostBookEntity method, or the PostBookDto Method?

Upvotes: 1

Views: 878

Answers (2)

Prokurors
Prokurors

Reputation: 2548

Actually it is a good idea to separate queries from data modifications (insert, update, delete) - this is called Command Query Responsibility Segregation pattern (CQRS).

Here are some great posts from experts

An introduction to CQRS by M.Fowler

Some good reasoning on why Entities + Dto's are better than just using Entities for all cases

Upvotes: 1

Chris Pratt
Chris Pratt

Reputation: 239260

Entities pretty much are DTOs. Use the entity for all database access, and use view models in your actions.

Upvotes: 0

Related Questions