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

Leo*_*ens 9 linq asp.net entity-framework asp.net-web-api

我使用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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Mau*_*ice 7

不要先选择内存中的所有内容.做这样的事情:

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Mapper.CreateMap<Item, ItemDto>()
    .ForMember(itemDto => itemDto.Category, mce => mce.MapFrom(item => item.Category.Name));
Run Code Online (Sandbox Code Playgroud)

  • 你应该在进入数据库之前执行`Take(20)`.否则,您将切换内存中的集合,这不是那么高效.代码:`var query = from context.Items.Take(20)中的item选择Mapper.Map(Item,ItemDto>(item);` (2认同)