【问题标题】:EF Core - Include ThenInclude InterfaceEF Core - 包含 ThenInclude 接口
【发布时间】:2019-03-12 09:56:53
【问题描述】:

我正在尝试使用.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)

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

我试图查找类似的案例,但没有找到。我是否遗漏了什么,或者这根本不可能,我正在尝试做一些你通常不应该做的事情?

即使不应该,你会如何做到这一点?

【问题讨论】:

  • 在 EF Core 2.0 中不能这样做。虽然 EF Core 2.1(现在在 rc1 中)应该是可能的

标签: c# asp.net-core entity-framework-core ef-core-2.0


【解决方案1】:

在 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 一起可用,可用于广泛测试,现在也可用于生产使用

【讨论】:

  • 太好了,想发表评论,您应该将其写为答案。我通读了 2.1 文档,其中包含一些我需要的功能。所以我现在就耐心等待吧。
  • 你可以使用 rc1. ASP.NET Core 也在 RC1 中,并且在构建过程中从微软获得了生产准备(至少 ASP.NET Core 做到了,EF Core 也应该这样做,它们是同步发布的)
  • 用 MSDN 博客文章更新了答案,宣布 EF Core 2.1 rc1 “也可用于生产”
  • 谢谢,很高兴看到我需要的功能最近刚刚推出。我会继续更新。
猜你喜欢
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-21
  • 1970-01-01
  • 2020-08-24
  • 2021-04-21
  • 1970-01-01
相关资源
最近更新 更多