C# 在自引用表中查找顶级实体

C# 在自引用表中查找顶级实体,c#,linq,entity-framework,lambda,C#,Linq,Entity Framework,Lambda,在实体框架中,如何搜索EF中处于顶层的对象 如果我有一组具有子零部件的部件。这些部件可以放置在较大的部件中 在一个真实的例子中:假设我们用一台计算机构建一个机柜,而计算机有一些部件。如何查找未安装在机柜中的计算机,或者可能是未安装在计算机中的部件 public class Component { public int Id { get; set; } public string Model { get; set; } public string PartId { get;

在实体框架中,如何搜索EF中处于顶层的对象

如果我有一组具有子零部件的部件。这些部件可以放置在较大的部件中

在一个真实的例子中:假设我们用一台计算机构建一个机柜,而计算机有一些部件。如何查找未安装在机柜中的计算机,或者可能是未安装在计算机中的部件

public class Component
{
    public int Id { get; set; }
    public string Model { get; set; }
    public string PartId { get; set; }
    public DateTime Manufactured { get; set; }
    public string SerialNumber { get; set; }
    public string ProductType { get; set; }
    public string Description { get; set; }
    public virtual List<Component> SubComponents { get; set; }
}
公共类组件
{
公共int Id{get;set;}
公共字符串模型{get;set;}
公共字符串PartId{get;set;}
公共日期时间{get;set;}
公共字符串序列号{get;set;}
公共字符串ProductType{get;set;}
公共字符串说明{get;set;}
公共虚拟列表子组件{get;set;}
}

我想我在这里找到了答案


你有一个有趣的标题。你能看到它生成的数据库结构吗?如果你的
组件
表有一个自引用外键,你可以检查外键何时为空。如果是这样的话,您必须更新您的模型以公开这些信息。@Hexa氰化物:您在Linux中杀过孤儿吗?;)没有孤儿,只有僵尸。修复了标题“没有父母的孩子”。我会说“周六晚上累了的程序员”。)
public class Component
{
    [Key]
    public int Id { get; set; }
    public string Model { get; set; }
    public string PartId { get; set; }
    public DateTime Manufactured { get; set; }
    public string SerialNumber { get; set; }
    public string ProductType { get; set; }

    //Added this...
    public int? ParentComponentId { get; set; }
    [ForeignKey("ParentComponentId")]
    public virtual Component ParentComponent { get; set; }

    public virtual List<Component> SubComponents { get; set; }
    public string Description { get; set; }
}
return _db.Components.Where(x => x.ParentComponent == null).ToList();