开发者

Linq to entities and Hierarchical table

I have a table with id and parentId columns the nesting level is just 1(for now).

Right now I load items like this:

using (KEntities ctx = new KEntities())
{
    ctx.KSet.MergeOption = MergeOption.NoTracking;

    var items = (from c in ctx.KSet
                 where c.ParentId == 0
                 select new
                 {
                     Title = c.Title,
                     Id = c.Id,                        开发者_运维技巧   
                     Subs = ctx.KSet.Where(o => o.ParentId == c.Id)                                      
                 }).ToList();

 }

The other option that I can choose is to set self-reference on the table, so the entity will expose self-navigation properties and then I can use Load() to load the children (lazy loading?).

Which approach is preferred and why?


IMHO, I prefer what you have done as in your example. I like to call the .ToList() cause then I know at that moment I have the data in memory, and don't have to worry about some of the problems you can have with Lazy loading.

"it leaks persistent storage access to different tiers via the lazy loadable associations." taken from link


The valid option is exposing navigation property Children and calling:

var items = ctx.KSet.Include("Children").Where(c => c.ParentId == 0);

This will allow you working directly with KSet entities. Projection will create a new type. In case of exposing navigation property you also have the choice of using eager loading (as shown in the example) or explicit / lazy loading if you want to. Projection make sense only if you want to filter or sort children.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜