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??

İsmet Alkan
  • 5,361
  • 3
  • 41
  • 64
garyson ford
  • 71
  • 1
  • 5
  • possible duplicate of [How to include a child object's child object in Entity Framework 5](http://stackoverflow.com/questions/13047845/how-to-include-a-child-objects-child-object-in-entity-framework-5) – Kritner Oct 31 '14 at 11:45

3 Answers3

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

garyson ford
  • 71
  • 1
  • 5
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.

Wojciech
  • 199
  • 9
  • 1
    do i have to write fluent api cause this is not working – garyson ford Oct 31 '14 at 12:10
  • 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. – Wojciech Oct 31 '14 at 13:46
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
xwrs
  • 1,287
  • 3
  • 16
  • 29