Eager Loading Using Fluent NHibernate/Nhibernate & Automapping
Asked Answered
D

4

25

I have a requirement to load a complex object called Node...well its not that complex...it looks like follows:-

A Node has a reference to EntityType which has a one to many with Property which in turn has a one to many with PorpertyListValue

public class Node
{
    public virtual int Id
    {
        get;
        set;
    }

    public virtual string Name
    {
        get;
        set;
    }

    public virtual EntityType Etype
    {
        get;
        set;
    }

}


public class EntityType
{
    public virtual int Id
    {
        get;
        set;
    }

    public virtual string Name
    {
        get;
        set;
    }

    public virtual IList<Property> Properties
    {
        get;
        protected set;
    }

    public EntityType()
    {
        Properties = new List<Property>();
    }
}

public class Property
{
    public virtual int Id
    {
        get;
        set;
    }

    public virtual string Name
    {
        get;
        set;
    }        

    public virtual EntityType EntityType
    {
        get;
        set;
    }

    public virtual IList<PropertyListValue> ListValues
    {
        get;
        protected set;
    }

    public virtual string DefaultValue
    {
        get;
        set;
    }

    public Property()
    {
        ListValues = new List<PropertyListValue>();
    }
}


public class PropertyListValue
{
    public virtual int Id
    {
        get;
        set;
    }

    public virtual Property Property
    {
        get;
        set;
    }

    public virtual string Value
    {
        get;
        set;
    }

    protected PropertyListValue()
    {
    }
}

What I a trying to do is load the Node object with all the child objects all at once. No Lazy load. The reason is I have thousands of Node objects in the database and I have to send them over the wire using WCF Service.I ran into the classes SQL N+ 1 problem. I am using Fluent Nhibernate with Automapping and NHibernate Profiler suggested me to use FetchMode.Eager to load the whole objects at once. I am using the following qyuery

     Session.CreateCriteria(typeof (Node))
            .SetFetchMode( "Etype", FetchMode.Join )
            .SetFetchMode( "Etype.Properties", FetchMode.Join )
            .SetFetchMode( "Etype.Properties.ListValues", FetchMode.Join )

OR using NHibernate LINQ

        Session.Linq<NodeType>()
         .Expand( "Etype")
         .Expand( "Etype.Properties" )
         .Expand( "Etype.Properties.ListValues" )

When I run any of the above query, they both generate one same single query with all the left outer joins, which is what I need. However, for some reason the return IList from the query is not being loaded property into the objects. Infact the returned Nodes count is equal to the number of rows of the query, so the Nodes objects are repeated.Moreover, the properties within each Node are repeated, and so do the Listvalues.

So I would like to know how to modify the above query to return all unique Nodes with the properties and list values within them.

Declarer answered 29/6, 2010 at 16:48 Comment(3)
On google I found out about DistinctRootEntityResultTransformer but that only resolve the issue for the Root objects. I am still getting duplicates in the child collections. Every root object in the returned list has some weird Cartesian product mess in the child collections with multiple instances of the same entity. Any idea? Awaiting NabeelDeclarer
I think I have found the solution but I would like to know if its the correct one. The child collections (EType.Properties, Etype.Properties.ListValues) inside root object (Node) are IList. And i read in the documentation that IList can contain duplicates, so if i change IList to ISet/ ICollection, then the query does not load duplicate instances within the child collections. But this solution requires alot of refactoring. I would like to know if there is a way to achieve the same using IList for child collections? Awaiting, NabeelDeclarer
I have the same issue (using Fetchmode.Eager). I'm pretty dissapointed in NHibernate for this. I would rather have an error than incorrect data.Instep
D
15

I figure it out myself. The key is to use SetResultTransformer() passing an object of DistinctRootEntityResultTransformer as a parameter. So the query now looks like as follows

Session.CreateCriteria(typeof (Node))
   .SetFetchMode( "Etype", FetchMode.Join )
   .SetFetchMode( "Etype.Properties", FetchMode.Join )
   .SetFetchMode( "Etype.Properties.ListValues", FetchMode.Join )
   .SetResultTransformer(new DistinctRootEntityResultTransformer());

I found the answer to my questions through these links:

http://www.mailinglistarchive.com/html/[email protected]/2010-05/msg00512.html

http://ayende.com/Blog/archive/2010/01/16/eagerly-loading-entity-associations-efficiently-with-nhibernate.aspx

Declarer answered 18/8, 2010 at 9:50 Comment(1)
+1, but Wow that's ugly. This just seems such a mess - I'm not impressed with Nibernate for this. Why should we need to transform the result? It seems like NH is not doing it's job properly.Instep
A
23

each mapping has to have lazy loading off

in Node Map:

Map(x => x.EntityType).Not.LazyLoad();

in EnityType Map:

Map(x => x.Properties).Not.LazyLoad();

and so on...

Also, see NHibernate Eager loading multi-level child objects for one time eager loading

Added:

Additional info on Sql N+1:

http://nhprof.com/Learn/Alerts/SelectNPlusOne

Anglonorman answered 29/6, 2010 at 18:27 Comment(8)
Thanks for the response Tim, Well I do not want to set the .Not.LazyLoad() in the mapping because it will then become default behaviour, and in my application I have a wcf service that that needs to pass data to the client and I want to load all the data at once in a single query to avoid SQL N+1 scenario (nhprof.com/Learn/Alerts/SelectNPlusOne). The rest of the application does not require eagerloading. So any idea how can I tackle this scenario?Declarer
Also my understanding is that .Not.LazyLoad does not solve the SQL N+1 problem. Fro mNhibernate profiler I have noticed that although it loads all the whole object graph in one go, it still generates more than one query, a query for each reference/hasmany object, that I do not want because I have thosands of nodes with hundered of entitytypes and properties and I do not want thosands unique queries to be generated. NabeelDeclarer
I thought you wanted it mapped that way. I added a link to another question that shows eager loading in a particular instance. I think this will help you produce a join. If not, you could look at righting a stored procedure and mapping it as a named query. See the original posters code in #1638362 for an example of thatAnglonorman
also, check out nhforge.org/blogs/nhibernate/archive/2008/09/06/…Anglonorman
Hi Tim, thanks for the info. Actually I am not having problem with generating the query. The query that gets generated is correct as exposed by nHibernate profiler. What strange is that the returned list of my objects has duplicats and every root object in the returned list has some weird Cartesian product mess in the child collections with multiple instances of the same entity but after using DistinctRootEntityResultTransformer and replacing child collections with ICollection instead of IList, it is working as I expected it to. But I would like to know if its the right solution or not ?Declarer
If you are getting ICollection instead of IList, it probably means you have mapped as a set instead of bag. If set is what you want, then I collection is right.Anglonorman
also check out FetchMode.Eager to try to load the objectsAnglonorman
I have exactly the same problem as Tim nabeeelfarid, but I'm using Fetchmode.Eager.Instep
D
15

I figure it out myself. The key is to use SetResultTransformer() passing an object of DistinctRootEntityResultTransformer as a parameter. So the query now looks like as follows

Session.CreateCriteria(typeof (Node))
   .SetFetchMode( "Etype", FetchMode.Join )
   .SetFetchMode( "Etype.Properties", FetchMode.Join )
   .SetFetchMode( "Etype.Properties.ListValues", FetchMode.Join )
   .SetResultTransformer(new DistinctRootEntityResultTransformer());

I found the answer to my questions through these links:

http://www.mailinglistarchive.com/html/[email protected]/2010-05/msg00512.html

http://ayende.com/Blog/archive/2010/01/16/eagerly-loading-entity-associations-efficiently-with-nhibernate.aspx

Declarer answered 18/8, 2010 at 9:50 Comment(1)
+1, but Wow that's ugly. This just seems such a mess - I'm not impressed with Nibernate for this. Why should we need to transform the result? It seems like NH is not doing it's job properly.Instep
T
9

I ended up with something like this:

HasMany(x => x.YourList).KeyColumn("ColumnName").Inverse().Not.LazyLoad().Fetch.Join()

Just make sure to select your entity like this, to avoid duplication due to the join:

session.CreateCriteria(typeof(T)).SetResultTransformer(Transformers.DistinctRootEntity).List<T>();
Togoland answered 12/10, 2011 at 19:9 Comment(1)
Can you do this with references too?Loss
E
4

SetResultTransformer with DistinctRootEntityResultTransformer will only work for Main object but IList collections will be multiplied.

Electrophoresis answered 21/12, 2010 at 20:16 Comment(1)
How will you use ISet or ICollection?Aerometeorograph

© 2022 - 2024 — McMap. All rights reserved.