ASP.NET Web API返回可查询的DTO?

我使用ASP.NET Web API构建了一个不错的API,但是我猜想从我的上下文(实体框架)AsQueryable返回实体是不对的,所以我将所有内容映射到DTO对象.

我还不太明白,我如何保持我的上下文可以查询,但仍然只返回DTO而不是实体?还是这不可能?

这是我的代码

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();
    }
}

正如你可以看到我加载数据,并使这个小的IEnumerable集合可查询.问题是,为这段代码生成查询可能是非常低效的,因为它首先加载所有项目(或至少20个第一个项目),然后过滤输出.

我希望我描述我的问题尽可能好,这有点难以解释.我在Google上找不到任何内容.

解决方法

不要先选择内存中的所有内容.做这样的事情:
public IQueryable<ItemDto> Get()
{
    using (EfContext context = new EfContext())
    {
        var query = from item in context.Items
                    select Mapper.Map<Item,ItemDto>(item)

        return query.OrderByDescending(x => x.PubDate).Take(20));
    }
}

BTW以下代码是您想要执行的操作,例如在静态构造函数或WebApiConfig.cs文件中.

Mapper.CreateMap<Item,ItemDto>()
    .ForMember(itemDto => itemDto.Category,mce => mce.MapFrom(item => item.Category.Name));

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...