在数据库上执行读取和 create/update 时使用实体和 DTO

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

执行数据库操作时实体和 DTO 的正确用法是什么?我的想法是,从数据库读取时最好使用 DTO,而当 creating/updating 读取到数据库时最好使用实体。作为一个小例子,让我们考虑以下内容:

图书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;}

}

作者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;}
}

现在,假设我们有一个 WebApi Book 控制器。

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
  }
}

哪个方法被认为是 "proper" PostBookEntity 方法或 PostBookDto 方法?

实体几乎 DTO。将实体用于所有数据库访问,并在您的操作中使用视图模型。

实际上 将查询与数据修改(插入、更新、删除)分开是一个好主意 - 这称为 Command Query Responsibility Segregation 模式 (CQRS)。

这里有一些来自专家的精彩帖子

An introduction to CQRS by M.Fowler

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