1

我的存储库层用于直接返回 ViewModel,例如

public IEnumerable<CommentViewModel> GetComments()
{
   return from c in context.Comments
                 select new CommentViewModel
                 {
                    FirstName = c.FirstName,
                    Comment = c.Comment
                 };
}

然后我读到存储库不应返回视图模型,因此我将其更改为:

public IEnumerable<Comment> GetComments()
{
   return from c in context.Comments;
}

然后在服务层中我更改了:

public IEnumerable<CommentViewModel> GetComments(int postId)
{
   return _repository.GetComments();
}

至:

public IEnumerable<CommentViewModel> GetComments()
{
   var comments = _repository.GetComments();

   return Mapper.Map<IEnumerable<Comment>, IEnumerable<CommentViewModel>>(comments);
}

问题是查询过去需要 7 毫秒,现在需要 85 毫秒!

我哪里错了?

生成的查询曾经是(前 5 个和 order by 在控制器中完成):

SELECT TOP (5) [t0].[FirstName], [t0].[Comment]
FROM [dbo].[Comment] AS [t0]
ORDER BY [t0].[CreateDate] DESC 

它现在返回所有列:

SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[FirstName] AS [FirstName], 
[Extent1].[LastName] AS [LastName], 
[Extent1].[DatePosted] AS [DatePosted], 
[Extent1].[Comment] AS [Comment],
[Extent1].[IPAddress] AS [IPAddress]
FROM [dbo].[Comment] AS [Extent1]
4

1 回答 1

3

您需要在存储库层中调整查询结果,否则 AutoMapper 将从数据库中提取所有记录以映射到视图模型。

public IEnumerable<Comment> GetComments(int skip, int count)
{
   return context.Comments.OrderByDescending(c => c.CreateDate).Skip(skip).Take(count);
}
于 2012-07-17T09:23:07.020 回答