I built a nice little API with the ASP.NET Web API, but I guess it's not right to return the entities from my context (entity framework) AsQueryable, so I'm mapping everything to DTO objects.
What I don't quite understand however: how can I keep my context queryable, but still only return DTO's instead of entities? Or is this not possible?
This is my code:
public IQueryable<ItemDto> Get()
{
using (EfContext context = new EfContext())
{
Mapper.CreateMap<Item, ItemDto>()
.ForMember(itemDto => itemDto.Category, mce => mce.MapFrom(item => item.Category.Name));
IEnumerable<ItemDto> data = Mapper.Map<IEnumerable<Item>, IEnumerable<ItemDto>>(context.Items
.OrderByDescending(x => x.PubDate)
.Take(20));
return data.AsQueryable();
}
}
As you can see I load the data, and make that little IEnumerable collection queryable. The problem is that the query that is generated for this piece of code is probably quite inefficient because it loads all the items first (or at least the 20 first items) and then filters the output.
I hope I described my problem as good as possible, it's a little bit hard to explain. I couldn't find anything about it on Google.