Reputation: 431
I have a Book class that contains an InventoryItem and the InventoryItem contains the Book, so the relationship is One to One. If I want to get the Inventory item it will return the Book that contains that InventoryItem and so on. I want to return that InventoryItem as IActionResult.
Book class:
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; }
InventoryItem class:
public Guid BookId { get; set; }
public Book Book { get; set; }
public int Number { get; set; }
public AcquisitionDetail AcquisitionDetail { get; set; }
The method that return InventoryItem:
public async Task<IEnumerable<InventoryItem>> GetInventoryItemsAsync()
{
return await schoolLibraryContext.InventoryItems.Include(inventoryItem => inventoryItem.Book)
.Include(inventoryItem => inventoryItem.AcquisitionDetail)
.ToListAsync();
}
Question: How can I include only one Book object without the InventoryItem when I want to return the InventoryItem.
Upvotes: 1
Views: 67
Reputation: 1276
I assume question is about Entity Framework, since it is in tags.
In terms of using data in app:
In such case, you don't really gave to worry about it. Unless you specifically ask about it using Include
, Book
will be lazy loaded, that is, it won't be sent in initial query, and in case you actually use it, another query will be sent to retrieve it.
Be wary though, lazy loading can save a lot of traffic, but it can also easily cause "N+1" problem, where you constantly send queries even though you could just load whole entity at once. So if you happen to actually use Book
later, it might be better idea to use Include
and load initially, executing queries is relatively expensive when compared to data traffic.
In terms of sending this data outside (through API)
Don't ever return your entity outside. It's really bad practice even if you actually want to return all of its properties.
If you return your data outside, you should map it to an object of other class, and then return this class. This way you make sure that you don't ever send too much data, e.g. by expanding your entity with properties you don't want to send outside.
In your case it could look like:
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; }
}
Upvotes: 1