Mert
Mert

Reputation: 6572

SetFetchMode Lazy doesn't overwrite ClassMap settings

In Criteria I do SetFetchMode as Lazy but still fetching all items, how can I fix this?

public class MenuItem : BaseClass<MenuItem>
{
    public virtual int MenuItemId { get; set; }
    public virtual string Text { get; set; }
    public virtual IList<MenuItem> Children { get; set; }
    public virtual MenuItem Parent { get; set; }

    public MenuItem()
    {
         Children = new List<MenuItem>();
    }
}

class MenuItemMap : ClassMap<MenuItem>
{
    public MenuItemMap()
    {
        Id(x => x.MenuItemId);
        Map(x => x.Text);
        HasMany(x => x.Children).KeyColumn("ParentId").Not.LazyLoad().Fetch.Select();
        References(x => x.Parent).Not.LazyLoad().Fetch.Select(); 
    }
}

using (var session = NHibernateHelper<T>.OpenSession())
{
    var CC = session.CreateCriteria(typeof(T));

    CC.SetFetchMode("Children", FetchMode.Lazy);

    return CC.List<T>();
}

Upvotes: 2

Views: 269

Answers (1)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123891

I have to say, that this is not possible. Our JAVA brother Hibernate (from which NHibernate was ported into .NET) seems to have that option:

But NHibernate does not support that. Chek also Override lazy loading behavior 'lazy=false'.

What we can do, is to bet on Projections. This way we really assemble exactly one SQL statement and get a list of Transformed objects (semi-filled, dependent on amount of selected properties)

16.6. Projections

Here is an example how to build a deep projections (including References/many-to-one)
Here is how to transform them into originally mapped object Graph.

Upvotes: 2

Related Questions