EF Core - How to retrieve base class and conditionally include property on derived class [duplicate]
Below is my model that captures the scenario of base class and derived class
Model
public class Group
{
List<Item> Items { get; set; }
}
public abstract class Item
{
public string Name { get; set; }
}
public class ItemWithResource : Item
{
public Resource Resource { get; set; }
}
public class ItemWithoutResource : Item
{
}
public class Resource
{
public decimal Price { get; set; }
}
- A Group has Items
- Each Item could be an ItemWithResource or an ItemWithoutResource
I want to retrieve all items, regardless of derived type, and also include the Resource for items that are ItemWithResource
return await _context.Groups
.Include(g => g.Items)
// NEXT LINE WILL NOT WORK AS BASE CLASS ITEM DOES NOT HAVE PROPERTY 'Resource'
.ThenInclude(i => i.Resource)
.SingleOrDefaultAsync();
The code snippet above illustrates the problem. How do I write a query to 'include' Resource for Items that are an ItemWithResource?
Solution 1:
try:
...
.ThenInclude( i => ( i as ItemWithResource ).Resource )
...