NHibernate -failed to lazily initialize a collection of role

后端 未结 3 1279
-上瘾入骨i
-上瘾入骨i 2021-02-07 03:04

I have the following seemingly simple scenario, however I\'m still pretty new to NHibernate.

When trying to load the following model for an Edit action on my Controller:

3条回答
  •  失恋的感觉
    2021-02-07 03:31

    You need to eagerly load the SomeOtherModel collection if you intend to use it before closing the session:

    using (ISession session = NHibernateSessionManager.Instance.GetSession())
    {
        return session
            .CreateCriteria()
            .CreateCriteria("SomeOtherModel", JoinType.LeftOuterJoin)
            .Add(Restrictions.Eq(Projections.Id(), id))
            .UniqueResult();
    }
    

    By default FluentNHibernate uses lazy loading for collection mappings. Another option is to modify this default behavior in your mapping:

    HasMany(x => x.SomeOtherModel)
        .KeyColumns.Add("key_id").AsBag().Not.LazyLoad();
    

    Note that if you do this SomeOtherModel will be eagerly loaded (using an outer join) every time you load the parent entity which might not be want you want. In general I prefer to always leave the default lazy loading at the mapping level and tune my queries depending on the situation.

提交回复
热议问题