c# - EF Core - 包含 ThenInclude 接口
问题描述
我正在尝试使用.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 和它们User
以及ApprovingUser
所有实现 Interface 的 TicketEntries IApprovable
。
我试过这样做:
_context.Ticket
.Include(t => t.TicketEntries)
.ThenInclude(te => te.User)
.Include(t => t.TicketEntries as ICollection<IApprovable>)
.ThenInclude(ia => ia.ApprovingUser)
这不起作用,因为它不是纯属性表达式。
我试图查找类似的案例,但没有找到。我是否遗漏了什么,或者这根本不可能,我正在尝试做一些你通常不应该做的事情?
即使不应该,你将如何做到这一点?
解决方案
不能在 EntityFramework Core 2.0 或更早版本中包含派生的。
有一个 GitHub 问题查询:支持 Include/ThenInclude 用于在请求此功能的派生类型上导航,该功能已添加到 EntityFramework Core 2.1-preview1。
根据2.1 文档和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 一起可用,可用于广泛的测试,现在也可用于生产用途!
推荐阅读
- javascript - 有没有办法在运行 puppeteer 时将表数据转换为 json?
- c# - 为什么 LINQ ToLookup 以对象为键执行缓慢
- regex - 正则表达式只允许少数特殊字符以及 az 或 AZ
- php - VSCode 中的编译时 PHP 错误
- python - 在 indicatorReleased() 事件处理程序中执行 Qscintilla 的“SCI_GOTOLINE”API 无法正常运行
- ios - iOS Swift - 如何获取本地和远程视频的纵横比?
- javascript - 从循环返回每个响应
- azure - 如何在 YAML 管道中克隆完整的 repo 而不是稀疏结帐?
- javascript - 尝试创建手风琴风格的常见问题解答
- javascript - 为第二个功能添加延迟