Search code examples
linqnhibernatelinq-to-nhibernate

Nhibernate - partial loading of objects


I have a MenuObject class that represents a websites Top Menu.

This object has amongst other properties, the following:

public class MenuObject
{
    public virtual int Id { get; set; }
    public virtual string Title { get; set; }
    public virtual List<MenuObject> Children { get; set; }
} 

The mapping has been configured to eagerly load the Children objects using the Not.LazyLoad() definition in fluent nhibernate.

I now have a problem where I want to use these objects to populate a breadcrumb control and a sidemenu control - For these controls, All I need is:

  • The ID and Title Properties
  • The Children collection (also only containing the above two properties)

I don't want to load ALL the properties of my main object as well as ALL the properties of eachchild object as it's just overkill.

I've managed to use Nhibernate Linq to retrurn ONLY properties of the main object, but how do I amend the query to do the same for child objects? (see ???)

return (from mnu in session.Query<MenuObject>()
       (select new MenuObject()
{
    Id = mnu.Id
    Title = mnu.Title,
    Children = ???
}

----------------EDIT---------------------

I've got this to work but I'm missing a where clause - this is setting the 'Children' to a list of all MenuObject instances regardless of relationship - obviously I only want it to add legitimate child objects to each parent object - can anyone assist? Thanks

from menuobject in session
    .Query<MenuObject>()
    where menuobject.Level == level
    select new MenuObject()
    {
        Title = menuobject.Title,
        Url = menuobject.Url,
        Children = session.CreateCriteria<MenuObject>()
                          .SetProjection(Projections.ProjectionList()
                          .Add(Projections.Property("Title"), "Title")
                          .Add(Projections.Property("Url"), "Url"))
                          .SetResultTransformer(Transformers.AliasToBean(typeof (MenuObject)))
                          .List<MenuObject>()
    }
    .ToList();

Solution

  • sorry i missed the multiple childs part. Also i would favor ViewModels or anonymous types instead of partial loaded Domainobjects which could cause confusion down the road.

    var results = (from mnu in session.Query<MenuObject>()
                   from ch in mnu.Children
                   select new
                   {
                       mnu.Id,
                       mnu.Title,
                       ChildTitle = ch.Title,
                       ch.Url
                   }).AsEnumerable()
                   .GroupBy(row => new { row.Id, row.Title })
                   .Select(gr => new
                   {
                       gr.Key.Id,
                       gr.Key.Title,
                       Children = gr.Select(c => new { c.ChildTitle, c.Url }).ToList()
                   });