My repository layer used to return a ViewModel directly e.g.
public IEnumerable<CommentViewModel> GetComments()
{
return from c in context.Comments
select new CommentViewModel
{
FirstName = c.FirstName,
Comment = c.Comment
};
}
I then read that the repository should not return view models so I changed it to:
public IEnumerable<Comment> GetComments()
{
return from c in context.Comments;
}
In the service layer I then changed:
public IEnumerable<CommentViewModel> GetComments(int postId)
{
return _repository.GetComments();
}
To:
public IEnumerable<CommentViewModel> GetComments()
{
var comments = _repository.GetComments();
return Mapper.Map<IEnumerable<Comment>, IEnumerable<CommentViewModel>>(comments);
}
The problem is the queries used to take 7ms and now take 85ms!
Where am I going wrong?
The query generated used to be (top 5 and order by is done in controller):
SELECT TOP (5) [t0].[FirstName], [t0].[Comment]
FROM [dbo].[Comment] AS [t0]
ORDER BY [t0].[CreateDate] DESC
It’s now returning all columns:
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]
You need to shape the query results in your repository layer otherwise AutoMapper will pull all the records from database to map to view models.