簡體   English   中英

EF core + Automapper ID-only 相關實體集合,如何?

[英]EF core + Automapper ID-only related entity collection, how?

我有一個簡單的問題 - 我希望其中一個 RESTful 端點服務於資源 DTO(自動映射),其相關資源僅作為它們的 ID。 但是,如果不加載整個(和繁重的)相關實體,似乎沒有任何方法可以實現它。 考慮以下(數據庫優先)示例模型:

public partial class Blog
{
    public int Id { get; set; }
    public string Url { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
}

public partial class Post // some heavy entity
{
    public int Id { get; set; }
    public string Content { get; set; }
    // other properties
}

及其對應的 DTO

// api/v1/blogs serves collection of following type
public class BlogSlimDto
{
    public int Id { get; set; }
    public string Url { get; set; }
    public int[] PostIds { get; set; }
}

一個直接的解決方案是從數據庫中獲取所有相關的Post並丟棄除 ID 之外的所有數據,但根據相關的Post實體大小,這可能效率低下甚至不可行:

var result = ctx.Blogs.Include(blog => blog.Posts) //fecth everything and discard it on next line
    .Select(blog => _mapper.Map<BlogSlimDto>(blog)); 
    // simply use a profile that discards Posts but keeps their Ids, e.g.
    // .forMember(dto => dto.PostIds, opt => opt.MapFrom(db.Posts.Select(p => p.Id)))

有一個類似的問題提供了一個使用匿名類型的解決方案,但是這在 Automapper 中根本不起作用:

var result = ctx.Blogs.Select(blog => new {
   blog.Id,
   blog.Url,
   PostIds = blog.Posts.Select(b => b.Id),
}).Select(ablog => _mapper.Map<BlogSlimDto>(ablog)); //throws, no mapping and such mapping cannot be defined

上面的代碼將在運行時拋出,因為沒有定義 Automapper 映射。 更糟糕的是,它無法定義,因為 Automapper 中不支持匿名類型 此外,一對一“手動”屬性分配的解決方案往往難以維護。
是否有替代解決方案允許 EF 查詢而不獲取整個相關實體,同時允許結果自動映射到BlogSlimDto

您可以使用可查詢的擴展:https ://docs.automapper.org/en/stable/Queryable-Extensions.html

var configuration = new MapperConfiguration(cfg =>
    cfg.CreateMap<OrderLine, OrderLineDTO>()
    .ForMember(dto => dto.Item, conf => conf.MapFrom(ol => ol.Item.Name)));

public List<OrderLineDTO> GetLinesForOrder(int orderId)
{
  using (var context = new orderEntities())
  {
    return context.OrderLines.Where(ol => ol.OrderId == orderId)
             .ProjectTo<OrderLineDTO>().ToList();
  }
}

用您的帖子和博客替換 Item 和 OrderLine

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM