0

I have an entity called

Public Class Equipment { int Id; string EquipmentName; int? ParentEquipmentId; } 

So have this entity where an equipment can have a parent and child relationship. I want to fetch the parent equipment and also all the children of the equipment associated with it.

Can i have ICollection on the entity to fetch me the childrens??

1

3 Answers 3

2
Public Class Equipment { int Id; string EquipmentName; int? ParentEquipmentId; virtual Equipment Parent; Virtual ICollection<Equipment> Childrens } 

Model binder use fluent api

 this.HasOptional(e => e.Parent) .WithMany(e => e.Children) .HasForeignKey(m => m.ParentEquipmentId); 

This will pull the records associated with the

Sign up to request clarification or add additional context in comments.

Comments

0

Yes you need to include collection of children in your object:

public virtual ICollection<Equipment> Children { get; set; } 

and remember to add .Include(q => q.Children) to your linq query to load children.

2 Comments

do i have to write fluent api cause this is not working
You can but you don't need to. Try to have you entity loaded properly first as it is. Then when you have it working add collection of children and in the query and 'Include' to load children. Also remember to initialize your collection in the constructor. If this doesn't answer your question please provide more details for my better understanding.
0

Seems that you need something like this (not the precise syntax)

Parent and Children properties:

public Equipment Parent { get { return dataContext.DbSet<Equipment>().SingleOrDefault(e=>e.Id == this.ParentEquipmentId); } } public IEnumerable<Equipment> Children { get { return dataContext.DbSet<Equipment>().Where(e=>e.ParentEquipmentId == this.Id); } } 

And use your Parent property to get all child Equipment of this particular parent:

this.Parent.Children 

2 Comments

How can i get all the childrens of the child assets
Use var allSubchild = this.Children.SelectMany(c => c.Children);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.