在执行数据库操作时,实体和 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/