我使用 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 个项目),然后过滤输出。
我希望我尽可能好地描述了我的问题,这有点难以解释。我在谷歌上找不到任何关于它的信息。
不要先选择内存中的所有内容。做这样的事情:
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));
}
}
顺便说一句,以下代码是您想要执行一次的操作,例如在静态构造函数中或在WebApiConfig.cs
file.
Mapper.CreateMap<Item, ItemDto>()
.ForMember(itemDto => itemDto.Category, mce => mce.MapFrom(item => item.Category.Name));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)