Asp.net
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)); } }順便說一句,以下程式碼是您想做一次的事情,例如在靜態建構子或
WebApiConfig.cs文件中。Mapper.CreateMap<Item, ItemDto>() .ForMember(itemDto => itemDto.Category, mce => mce.MapFrom(item => item.Category.Name));