Reputation: 2463
In Entity Framework, how do I search for objects that are at the top level in EF?
If I have a group of subassemblies that have subcomponents. Those subassemblies can be placed in larger assemblies.
In a real world example: Let's say we build a cabinet with a computer and the computer has parts. How do I find the computers that have not been installed in a cabinet or, perhaps, parts not installed in a computer?
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; }
}
Upvotes: 2
Views: 589
Reputation: 2463
I think I found my answer here...Self Referencing Tables
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; }
}
Originally I was trying to add a Foreign Key to the SubComponents but I actually needed a FK on the parent relationship. Now my EF query looks like this...
return _db.Components.Where(x => x.ParentComponent == null).ToList();
Upvotes: 3