Gus
Gus

Reputation: 896

Entity Framework 4 - Include self-related table

I have an self-related table:

UnitID    UnitParentID   Name

Code to retrieve 1 level :

return contexto.unit
             .Include("unit1")

Code to retrieve 2 levels :

return contexto.unit
             .Include("unit1.unit1")

Code to retrieve 3 levels :

return contexto.unit
             .Include("unit1.unit1.unit1")

How do I do this for many levels?

Upvotes: 4

Views: 661

Answers (2)

Julian
Julian

Reputation: 1294

I have had that Problem these days and resolved it like this.

You have to load all entites first like:

List<unit> myUnits = (from o in ctx.unit
                     .Expand("units")
                      select o).ToList();

After that you have to select these units you want to have like:

var selectedUnits = myUnits.Where(u => u.Property == x).ToList();

This works fine for me! Hope I could help you!

Best regards Julian

Upvotes: 2

Michael
Michael

Reputation: 107

Short answer: You don't.

Longer answer: You add an extra column to unit to identify unit's belonging together. Then you do something like:

var tempResult = myDataContext.unit.Where(x => x.id == id);
return tempResult.FirstOrDefault(); //or some other logik to return the correct 'first' unit.

Upvotes: 1

Related Questions