EF Core, include derived type property

Viewed 524

I have a small problem with a specific include statement. My datastructure is as follows:

[Table("item")]
public class Item
{
  public int Id { get; set; }
  public string ItemCode { get; set; }
  ...
}

public abstract class DerivedItemAbstractBase : Item
{
  [ForeignKey("ItemId")]
  public List<Assignment> Assignments { get; set; }
  ...
}

[Table("item")]
public class DerivedItemA : DerivedItemAbstractBase
{
  ...
}

[Table("item")]
public class DerivedItemB : DerivedItemAbstractBase
{
  ...
}

public class ItemContext : DbContext
{
  public DbSet<Item> Items { get; set; }
  ...
}

Now I want to get a list of all DerivedItemA and include properties of it. I have the following method:

public List<DerivedItemA> GetDerivedItemsA()
{
  var list = _context.Items
             .Include(x => (x as DerivedItemA).Assignments)
             .ToList();
}

This code compiles just fine and is something I have found on stackoverflow. However executing this results in an exception with the short message Invalid include. I dont know how to solve this problem. The project is a database-first approach so I have no control over the database. All items are stored in the same table item. I cannot create multiple DbSets because there is no discriminator column in the table and I cannot configure a custom discriminator in code because it would need to discriminate based on multiple properties and not a single property.

Is there any other way of doing this? Currently I am solving it by iterating through all ItemContext.Items then doing a .Select() on each and creating a new DerivedItemA. After that I manually set every Assignment by iterating from the Assignment table. However this approach takes far too long and it would be a lot quicker if I could just include it in the initial query.

0 Answers
Related