views:

957

answers:

2

Hi, i have standart self-referencing table of categories. In entity model i have made association "Children" and "Parent". It is possible to load whole Category object without lazy loading?

if i use the code bellow, it's load only to second level (depth).

db.Categories.MergeOption = System.Data.Objects.MergeOption.NoTracking;

var query = from c in db.Categories.Include("Children")
            where c.IsVisible == true
            orderby c.SortOrder, c.Id
            select c;

It is possible to load references if i have all the category objects allready loaded?

One method to load it is add children property multipletimes

db.Categories.Include("Children.Children.Children.Children.Children")

but it generates very long insane T-SQL code and also it doesn't do what i want..

+1  A: 

Ok, you might consider using Load method.

 if (!category.Children.IsLoaded)
        category.Children.Load();

Of course, category entity need to be tracked by ObjectContext.

There is better explanation here how-does-entity-framework-work-with-recursive-hierarchies-include-seems-not-to.

Misha N.
I know this method (it will generate hundrets of T-SQL queries), but also i muss load it without tracking, because i'm saving it into cache. I'm looking for something else. If i load whole table of categories, i have loaded also parents and children categories, but the association properties are not loaded. Also i have related table of CategoryType and i muss load it for each category regardless of they referenced the same row...
Jan Remunda
Ok, i didn't see that you have to cache it. Hmm, I'll try to think how this could be solved.
Misha N.
A: 

No, it isn't possible. Consider: All LINQ to Entities queries are translated into SQL. Which SQL statement includes an unlimited depth in a self-referencing hierarchy? In standard SQL, there isn't one. If there's an extension for this in T-SQL, I don't know what it is, and I don't think EF providers do, either.

Craig Stuntz
But if i run query "SELECT * FROM Categories" i have loaded whole table and also i have loaded all parent and children categories, because they're all in one table. So in this case it isn't very complicated to assign this loaded records to referenced properties, or not?
Jan Remunda
If you actually iterated the entire table, then all the objects *would* be in memory and *would* already be fixed up, with or without Include. But that won't happen until you have reached the last record in the table. Include guarantees that the related objects will be there on the *first* record you iterate.
Craig Stuntz