asp.net-mvc - 在数据库上执行读取和创建/更新时使用实体和 DTO

标签 asp.net-mvc database asp.net-web-api crud dto

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

读书课

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

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

}

作者类/实体

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

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

BookAuthorDto 类

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

现在,假设我们有一个 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
  }
}

PostBookEntity 方法或 PostBookDto 方法哪个方法被认为更“合适”?

最佳答案

实际上,将查询与数据修改(插入、更新、删除)分开一个好主意 - 这称为命令查询责任分离模式 (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

关于asp.net-mvc - 在数据库上执行读取和创建/更新时使用实体和 DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29951393/

相关文章:

angularjs - 带有 Angular 前端的 Web Api OAuth - 无法处理 302 重定向

http - 哪个 URL 应该用于子资源的 GET、PUT 和 DELETE?

jquery - MVC 帮助链接 Url.Action 不再解析

asp.net-mvc - API 仅在 fiddler 运行时有效

php - 从表中选择 * 不起作用

asp.net - 尝试通过方法 'HttpConfiguration..ctor(HttpRouteCollection)' 访问方法 'HttpConfiguration.DefaultFormatters()' 失败

asp.net-mvc - 使用 C# 以编程方式向 MVC Controller 验证 Azure Ad/OpenId 并获取重定向 uri

c# - mvc5 全局认证检查

mysql - 通常来说,公司 "A"使用 MySQL 作为数据库。它是指 MySQL 免费版还是 MySQL 企业版?

regex - 从 r 中的字符串中提取时间