Reputation: 748
I am trying to load related data using .Include().ThenInclude()
. I am using inheritance and my classes deriving from the base class TicketEntry
can implement an interface IApprovable
:
public class Ticket
{
[Key]
public int Id { get; set; }
[Required]
public string Title { get; set; }
public ICollection<TicketEntry> TicketEntries { get; set; }
}
public abstract class TicketEntry
{
[Key]
public int Id { get; set; }
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreationDate { get; set; }
[Required]
public string UserId { get; set; }
[ForeignKey("UserId")]
public ApplicationUser User { get; set; }
public int TicketId { get; set; }
[ForeignKey("TicketId")]
public Ticket Ticket { get; set; }
}
public class Common : TicketEntry
{
[Required]
public string Description { get; set; }
}
public class CostEstimate : TicketEntry, IApprovable
{
[Required]
[Column(TypeName = "money")]
public decimal Estimate { get; set; }
public Boolean? Approved { get; set; }
public string ApprovingUserId { get; set; }
[ForeignKey("ApprovingUserId")]
public ApplicationUser ApprovingUser { get; set; }
}
Now I want to get a Ticket
with all it's TicketEntries and their User
and the ApprovingUser
for all the TicketEntries implementing the Interface IApprovable
.
I tried doing this:
_context.Ticket
.Include(t => t.TicketEntries)
.ThenInclude(te => te.User)
.Include(t => t.TicketEntries as ICollection<IApprovable>)
.ThenInclude(ia => ia.ApprovingUser)
Which doesn't work since it's not a pure property expression.
I tried to look up similar cases but couldn't find any. Am I missing something or is that simply not possible and I'm trying to do something you normally should not do?
Even if one shouldn't, how would you accomplish this?
Upvotes: 1
Views: 1155
Reputation: 64121
It's not possible to include derived in EntityFramework Core 2.0 or older.
There is an GitHub Issue Query: Support Include/ThenInclude for navigation on derived type requesting this feature, which was added to EntityFramework Core 2.1-preview1.
As per 2.1 documentation and What's new in 2.1 you can use it via one of the following syntax:
var option1 = context.People.Include(p => ((Student)p).School);
var option2 = context.People.Include(p => (p as Student).School);
var option3 = context.People.Include("School");
https://blogs.msdn.microsoft.com/dotnet/2018/05/07/announcing-entity-framework-core-2-1-rc-1/
Today, we are excited to announce that the first release candidate of EF Core 2.1 is available, alongside .NET Core 2.1 RC 1 and ASP.NET Core 2.1 RC 1, for broad testing, and now also for production use!
Upvotes: 2