You cannot force all parents to use any reasonable code in one trip.
However, you can do something like this: fooobar.com/questions/174990 / ...
By changing your essence a bit, you can add 2 derived collections:
public class Item { [Key] public int ItemId { get; set; } [Required] [MaxLength(255)] public string Name { get; set; }} public virtual Item Parent { get; set; } // be sure to make this virtual public virtual List<Item> Children { get; set; } public virtual ICollection<ItemNode> Ancestors { get; set; } public virtual ICollection<ItemNode> Offspring { get; set; } }
You need to introduce a new object to do this job, which looks like this:
public class ItemNode { public int AncestorId { get; set; } public virtual Item Ancestor { get; set; } public int OffspringId { get; set; } public virtual Item Offspring { get; set; } public int Separation { get; set; }
Now if you want
all parents from ItemId 55 until no parents are found
... you can do something like this:
IEnumerable<Item> allParentsFrom55 = dbContext.Set<Item>() .Find(55).Ancestors.Select(x => x.Ancestor);
source share