Reputation: 71
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??
Upvotes: 0
Views: 214
Reputation: 71
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
Upvotes: 2
Reputation: 1297
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
Upvotes: 0
Reputation: 234
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.
Upvotes: 0