Search code examples
asp.net-mvcdatabaseasp.net-web-apicruddto

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?


Solution

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