EF Core - 包含ThenInclude接口

问题描述 投票:1回答:1

我正在尝试使用.Include().ThenInclude()加载相关数据。我正在使用继承,我的类派生自基类TicketEntry可以实现一个接口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; }
}

现在我想得到一个Ticket,其中包含所有的TicketEntries及其UserApprovingUser,用于实现接口IApprovable的所有TicketEntries。

我试过这样做:

_context.Ticket
    .Include(t => t.TicketEntries)
        .ThenInclude(te => te.User)
    .Include(t => t.TicketEntries as ICollection<IApprovable>)
        .ThenInclude(ia => ia.ApprovingUser)

哪个不起作用,因为它不是纯属性表达式。

我试图查找类似的案例,但找不到任何。我错过了什么或者根本不可能而且我正在尝试做一些你通常不应该做的事情?

即使不应该,你会怎么做到这一点?

c# asp.net-core entity-framework-core ef-core-2.0
1个回答
2
投票

在EntityFramework Core 2.0或更早版本中包含派生是不可能的。

有一个GitHub问题Query: Support Include/ThenInclude for navigation on derived type请求此功能,该功能已添加到EntityFramework Core 2.1-preview1。

根据2.1 documentationWhat's new in 2.1,您可以通过以下语法之一使用它:

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");

更新:建立2018公告和生产准备

https://blogs.msdn.microsoft.com/dotnet/2018/05/07/announcing-entity-framework-core-2-1-rc-1/

今天,我们很高兴地宣布EF Core 2.1的第一个候选版本,以及.NET Core 2.1 RC 1和ASP.NET Core 2.1 RC 1,可用于广泛的测试,现在也可用于生产!

© www.soinside.com 2019 - 2024. All rights reserved.