【问题标题】:I cannot turn off lazy loading in NHibernate我无法在 NHibernate 中关闭延迟加载
【发布时间】:2017-12-13 07:25:04
【问题描述】:

我知道延迟加载 'on' 是 NHibernate 中的默认设置。我关闭了延迟加载,使用按代码映射,用于实体(学生)和实体中包含的集合(评论)。然而,包括使用 SQL-Profiler 的测试表明,当通过 Session.Get() 访问实体时,它不会从数据库加载集合。我只看到一个“选择”来从数据库中获取实体(学生)。没有“加入”或“选择”到集合表(评论)。我错过了什么吗?我正在使用 NH 版本 5。

映射:

using NHibernate.Mapping.ByCode.Conformist;
using NHibernate.Mapping.ByCode;

namespace Infrastructure.Repository.NH.Tests
{
    public class StudentSubclassMapping: JoinedSubclassMapping<Student>
    {
        public StudentSubclassMapping()
        {
            Lazy(false);
            Property(student => student.EnrollmentDate);

            List(student => student.Comments,
                listMapper =>
                { listMapper.Lazy(CollectionLazy.NoLazy);},
                relationMapper =>
                     relationMapper.Element());
        }
    }
}

域:

public class Student : Contact
{
    public virtual DateTime? EnrollmentDate { get; set; }
    public virtual IList<string> Comments { get; set; }
}

测试:

    public void Get_TestToCheckIfLazyLoadingIsTurnedOff()
    {
        using (var session = SessionFactory.OpenSession())
        {
            using (var transaction = session.BeginTransaction())
            {
                var student = session.Get<Student>(2);
                transaction.Commit();
            }
        }
    }

【问题讨论】:

    标签: nhibernate lazy-loading nhibernate-mapping-by-code


    【解决方案1】:

    刚刚使用 NHibernate 5.0.3 对此进行了测试,它似乎工作正常:

    NHibernate: SELECT student0_.student_key as id1_0_0_, student0_.EnrollmentDate as enrollmentdate2_1_0_ FROM Student student0_ inner join Contact student0_1_ on student0_.student_key=student0_1_.Id WHERE student0_.student_key=@p0;@p0 = 1 [Type: Int32 (0:0:0)]
    NHibernate: SELECT comments0_.student_key as student1_2_0_, comments0_.id as id2_2_0_, comments0_.idx as idx3_0_ FROM Comments comments0_ WHERE comments0_.student_key=@p0;@p0 = 1 [Type: Int32 (0:0:0)]
    

    您已经拥有的listMapper.Lazy(CollectionLazy.NoLazy) 应该可以解决问题。

    我认为也许您的数据库中实际上并没有 ID 为 2 的学生? 如果是这种情况,您将只会看到 NHibernate 发出第一个查询(通过 Contact/Student),它不会对 Comments 发出查询,因为 Student 不存在。

    如果您有一个 ID 为 2 的学生,您应该会在第一个查询之后看到对 Comments 表的查询。

    如果您愿意,可以尝试添加 listMapper.Fetch(CollectionFetchMode.Join) 以在同一查询中同时包含学生和评论,尽管我通常不建议这样做。

    【讨论】:

    • 是的,就是这样,我在数据库中没有实体。否则效果很好。
    猜你喜欢
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    • 2013-12-10
    • 2011-10-17
    • 1970-01-01
    相关资源
    最近更新 更多