【发布时间】:2020-07-22 13:50:32
【问题描述】:
我需要帮助将连接表提取为上下文 linq-syntax 表达式中的集合。
public class Computer
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Component
{
public int Id { get; set; }
public string Name { get; set; }
public int ComputerId { get; set; } //FK
public Computer Computer { get; set; } //HasOne(Computer).WithMany().HasFK(ComputerId)
}
计算机没有组件的反向引用
需要通过Linq-syntax选择有相关组件的电脑。
(from computer in db.Computers
join component in db.Components on computer.Id equals component.ComputerId into components //| JOINED
from component in components.DefaultIfEmpty() //| TABLE
select new ComputerFullData
{
Computer = computer,
Components = components // <-- collection
})
........other code
此 linq 不起作用并生成 NullRefException
但是,如果 Computer 具有 ICollection backref 属性,那么我可以通过调用 Include(x = > x.Components) 实际上是 revert-JOIN 就像我的例子一样。在这种情况下,我可能无法访问组件集合。
我怎样才能通过 Linq 达到同样的效果?
【问题讨论】:
标签: c# .net entity-framework linq entity-framework-core