Nhibernate join on a table twice

Posted by Zuber on Stack Overflow See other posts from Stack Overflow or by Zuber
Published on 2010-05-21T15:49:21Z Indexed on 2010/05/21 15:50 UTC
Read the original article Hit count: 321

Consider the following Class structure...

public class ListViewControl
{
    public int SystemId {get; set;}
    public List<ControlAction> Actions {get; set;}
    public List<ControlAction> ListViewActions {get; set;}
}

public class ControlAction
{
    public string blahBlah {get; set;}
}

I want to load class ListViewControl eagerly using NHibernate. The mapping using Fluent is as shown below

public UIControlMap()
    {
        Id(x => x.SystemId);
        HasMany(x => x.Actions)
            .KeyColumn("ActionId")
            .Cascade.AllDeleteOrphan()
            .AsBag()
            .Cache.ReadWrite().IncludeAll();
        HasMany(x => x.ListViewActions)
            .KeyColumn("ListViewActionId")
            .Cascade.AllDeleteOrphan()
            .AsBag()
            .Cache.ReadWrite().IncludeAll();
    }

This is how I am trying to load it eagerly

var baseActions = DetachedCriteria.For<ListViewControl>()
            .CreateCriteria("Actions", JoinType.InnerJoin)                
            .SetFetchMode("BlahBlah", FetchMode.Eager)
            .SetResultTransformer(new DistinctRootEntityResultTransformer());

var listViewActions = DetachedCriteria.For<ListViewControl>()
            .CreateCriteria("ListViewActions", JoinType.InnerJoin)
            .SetFetchMode("BlahBlah", FetchMode.Eager)
            .SetResultTransformer(new DistinctRootEntityResultTransformer());

var listViews = DetachedCriteria.For<ListViewControl>()
            .SetFetchMode("Actions", FetchMode.Eager)
            .SetFetchMode("ListViewActions",FetchMode.Eager)
            .SetResultTransformer(new DistinctRootEntityResultTransformer());

var result = _session.CreateMultiCriteria()
                .Add("listViewActions", listViewActions)
                .Add("baseActions", baseActions)
                .Add("listViews", listViews)
                .SetResultTransformer(new DistinctRootEntityResultTransformer())
                .GetResult("listViews");

Now, my problem is that the class ListViewControl get the correct records in both Actions and ListViewActions, but there are multiple entries of the same record. The number of records is equal to the number of joins made to the ControlAction table, in this case two.

How can I avoid this? If I remove the SetFetchMode from the listViews query, the actions are loaded lazily through a proxy which I don't want.

© Stack Overflow or respective owner

Related posts about nhibernate

Related posts about criteria-api