【发布时间】:2015-10-07 04:25:47
【问题描述】:
我已阅读存储库不应返回 DTO 而是实体。那么如何返回具有子实体数量的实体列表?
这是我在数据库中的实体:
public class Note
{
[Key]
public int NoteId { get; set; }
[Required]
public string Content { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
现在我在存储库中:
public IEnumerable<Note> GetNotes()
{
return context.Notes.OrderBy(x => x.Title).ToList();
}
并在服务中:
public class NoteWithCommentsCountDTO
{
public Note Note { get; set; }
public int NoteCommentsCount { get; set; }
}
public IEnumerable<NoteWithCommentsCountDTO> GetNotesWithNoSpamCommentsCount()
{
IEnumerable<NoteWithCommentsCountDTO> notesDTO = _notesRepository.GetNotes()
.Select(x =>
new NoteWithCommentsCountDTO
{
Note = x,
NoteCommentsCount = x.Comments.Where(y => y.IsSpam == false).Count()
});
return notesDTO;
}
不幸的是,Entity Framework 生成的 SQL 查询与注释的数量一样多。
如果我在存储库中使用 DTO,我可以消除这个问题:
public IEnumerable<NoteWithCommentsCountDTO> GetNotesWithNoSpamCommentsCount()
{
IQueryable<NoteWithCommentsCountDTO> notesDTO = context.Notes
.Include(x => x.Comments)
.OrderBy(x => x.Title)
.Select(x =>
new NoteWithCommentsCountDTO
{
Note = x,
NoteCommentsCount = x.Comments.Where(y => y.IsSpam == false).Count()
}).ToList();
return notesDTO;
}
现在实体框架生成一个 SQL 查询,但我从存储库返回 DTO,而不是实体 - 解决方案是什么?
【问题讨论】:
-
从存储库返回 DTO。这是完全可以接受的。
标签: c# entity-framework data-access-layer dto