Nhibernate两次加入桌面

时间:2010-05-21 15:49:21

标签: c# nhibernate eager-loading criteria-api detachedcriteria

考虑以下类结构...

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;}
}

我想使用NHibernate加载类ListViewControl 急切。 使用Fluent的映射如下所示

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();
    }

这就是我试图加载它的方式

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");

现在,我的问题是类ListViewControlActionsListViewActions中都获得了正确的记录,但同一条记录中有多个条目。记录数等于ControlAction表的连接数,在本例中为两个。

我该如何避免这种情况?如果我从SetFetchMode查询中删除listViews,则会通过我不想要的代理延迟加载操作。

我也尝试过创建别名......

.SetFetchMode("Actions", FetchMode.Eager)
.CreateAlias("Actions","actions",JoinType.RightOuterJoin)
.SetFetchMode("ListViewActions",FetchMode.Eager)
.CreateAlias("ListViewActions", "liactions", JoinType.RightOuterJoin)

这删除了重复的条目,但没有急切加载

1 个答案:

答案 0 :(得分:0)

这是一种非常低效的急切加载集合方式。这是一个更好的方法:

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