我用ASP.NET Web API构建了一个不错的API,但是我想从我的上下文( Entity Framework )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));
}
}
顺便说一句,以下代码是您想执行的一次操作,例如在静态构造函数中或在
WebApiConfig.cs
文件中。Mapper.CreateMap<Item, ItemDto>()
.ForMember(itemDto => itemDto.Category, mce => mce.MapFrom(item => item.Category.Name));
关于ASP.NET Web API返回可查询的DTO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9894369/