ASP.NET的Web API返回可查询的DTO? [英] ASP.NET Web API return queryable DTOs?

查看:96
本文介绍了ASP.NET的Web API返回可查询的DTO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立的的ASP.NET Web API一个不错的API,但我想这是不对的,从我的背景下(实体框架)AsQueryable已返回实体,所以我映射一切DTO对象。

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.

我不太明白不过:我怎样才能让我的情况下可查询,但仍只返回DTO的,而不是实体?或者,这是不可能的?

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?

这是我的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();
    }
}

正如你可以看到我加载数据,并进行了小IEnumerable集合可查询。问题是,被用于这个片$ C $的c生成的查询可能是非常低效的,因为它第一次加载的所有项目(或至少20首先项),然后过滤输出

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.

推荐答案

不要首先选择在内存中的一切。做这样的事情:

Don't select everything in memory first. Do something like this:

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以下code是你想要做一次,例如在静态构造函数或在 WebApiConfig.cs 文件什么的。

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

这篇关于ASP.NET的Web API返回可查询的DTO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆