c# - session 关闭后加载子对象

标签 c# nhibernate fluent-nhibernate lazy-loading

我想在 session 关闭后加载一个子对象,无论如何都要这样做?

using (var session = NHibernateHelper<T>.OpenSession())
{
    Foo = session.CreateCriteria(Foo).List<Foo>();
}

using (var session = NHibernateHelper<T>.OpenSession())
{
     Foo.Children.Load();
}


public static void Load<T>(this IList<T> list)
{
     //load foo with Children
}

最佳答案

我们可以在这里受益于 NHibernate 对分离对象的原生支持

19.1.4. Initializing collections and proxies

...
You may also attach a previously loaded object to a new ISession with Merge() or Lock() before accessing uninitialized collections (or other proxies). No, NHibernate does not, and certainly should not do this automatically, since it would introduce ad hoc transaction semantics!
...

调整后的 Load() 方法如下所示:

public static TEntity LoadCollection<TEntity, TItem>(
        this TEntity entity, 
        Func<TEntity, IList<TItem>> listGetter)
    where TEntity : class
{
    using (var session = NHibernateHelper<T>.OpenSession())
    {
        // here we get brand new - connected - instance of TEntity
        TEntity reAttached = session.Merge<TEntity>(entity);

        NHibernate.NHibernateUtil
            .Initialize(listGetter.Invoke(reAttached));

        return reAttached;
    }
}

调用方:

using (var session = NHibernateHelper<T>.OpenSession())
{
    IList<Foo> foos = session.CreateCriteria<Foo>()
            ...
            .List<Contact>();
}

Foo foo = foos.First();

// here we get merged instance with initiated
foo =  foo.LoadCollection(f => f.SomeCollection);

注意:这真的取决于我们为什么需要它。合并将需要更改引用(旧的分离对象将丢失)。
有时可能足以(甚至更好)将集合加载为 IList<TItem>直接,通过 session ,使用 Where ParentId = current.ID ...只是一个想法...

关于c# - session 关闭后加载子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30170081/

相关文章:

NHibernate 组件映射 VS IUserType

c# - 将动态组件映射到不友好的数据表结构?

c# - 检查上次执行 Windows 更新检查的时间

c# - 从 C# 程序进行打印的最佳方法是什么?

c# - 我应该如何开始玩 3D?

c# - 无需调用 session.Insert 或 session.Save 即可获取 HiLo 号码

database - Fluent NHibernate 的类映射生成器

c# - Avalonia 按钮单击事件不起作用

hibernate - HQL 42P01 : missing FROM-clause entry for table

nhibernate - Fluent NHibernate - SessionSource 和 PersistenceSpecification