代码之家  ›  专栏  ›  技术社区  ›  Eduard Stefanescu

如何在没有一个相关实体的情况下获得一对一对象?

  •  1
  • Eduard Stefanescu  · 技术社区  · 7 年前

    我有一个包含InventoryItem的Book类,InventoryItem包含图书,所以关系是一对一的。如果我想得到库存项目,它将返回包含该库存项目的书籍等。我想把那个库存项目作为IActionResult返回。

    public string Title { get; set; }
    public IEnumerable<Author> Authors { get; set; }
    public Category Category { get; set; }
    public string Isbn { get; set; }
    public string PublishingHouse { get; set; }
    public string Edition { get; set; }
    public InventoryItem InventoryItem { get; set; }
    public bool IsDamaged { get; set; }
    public bool IsLost { get; set; }
    

    库存项目类别:

    public Guid BookId { get; set; }
    public Book Book { get; set; }
    public int Number { get; set; }
    public AcquisitionDetail AcquisitionDetail { get; set; }
    

    返回InventoryItem的方法:

    public async Task<IEnumerable<InventoryItem>> GetInventoryItemsAsync()
    {
        return await schoolLibraryContext.InventoryItems.Include(inventoryItem => inventoryItem.Book)
            .Include(inventoryItem => inventoryItem.AcquisitionDetail)
            .ToListAsync();
    }
    

    问题:

    1 回复  |  直到 7 年前
        1
  •  1
  •   Arion S.Frank Richarrd    7 年前

    我假设问题是关于实体框架的,因为它在标记中。

    在这种情况下,你真的不用担心。除非你特别询问 Include , Book

    不过,要小心,延迟加载可以节省大量流量,但它也很容易导致“N+1”问题,即即使可以一次加载整个实体,也会不断发送查询。所以如果你真的使用 包括 而且在最初加载时,与数据通信量相比,执行查询相对昂贵。

    将数据发送到外部(通过API)

    永远不要把你的实体放在外面。即使你真的想归还它的所有属性,这也是一个非常糟糕的做法。

    如果在外部返回数据,则应将其映射到其他类的对象,然后返回该类。通过这种方式,您可以确保永远不会发送太多数据,例如,使用不希望发送到外部的属性扩展实体。

    在你的情况下,它可能看起来像:

    public class BookModel
    {
        public string Title { get; set; }
        public IEnumerable<AuthorModel> Authors { get; set; }
        public Category Category { get; set; }
        public string Isbn { get; set; }
        public string PublishingHouse { get; set; }
        public string Edition { get; set; }
        public bool IsDamaged { get; set; }
        public bool IsLost { get; set; }
    }
    
    public class InventoryItemModel
    {
        public Guid BookId { get; set; }
        public BookModel Book { get; set; }
        public int Number { get; set; }
        public AcquisitionDetailModel AcquisitionDetail { get; set; }
    }