如何正确测试 NHibernate FetchMode.Eager?

发布于 2024-07-25 03:27:49 字数 361 浏览 3 评论 0 原文

有没有办法编写集成测试来测试 FetchMode.Eager 是否正常工作? 我想验证当我检索 MySubObject 时它不会进入数据库。

代码:

public MyObject GetEager(string name)
{
    return Session
        .CreateCriteria(typeof(MyObject))
        .SetFetchMode("MySubObject", FetchMode.Eager)
        .Add(Restrictions.Eq("Name", name))
        .UniqueResult<MyObject>();
}

Is there any way to write an integration test to test that the FetchMode.Eager works correctly? I want to verify that it's not going to the database when I retrieve MySubObject.

The code:

public MyObject GetEager(string name)
{
    return Session
        .CreateCriteria(typeof(MyObject))
        .SetFetchMode("MySubObject", FetchMode.Eager)
        .Add(Restrictions.Eq("Name", name))
        .UniqueResult<MyObject>();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暮色兮凉城 2024-08-01 03:27:49

您还可以使用 NHibernateUtil.IsInitialized... 如本文所述

http://nhibernate.info/doc/howto/various/lazy-loading-eager-loading.html

You can also use NHibernateUtil.IsInitialized... as explained in this post

http://nhibernate.info/doc/howto/various/lazy-loading-eager-loading.html

没︽人懂的悲伤 2024-08-01 03:27:49

像这样的事情怎么样?

MyObject testObject = new MyObject();
testObject.GetEager("a name");
testObject.Session.Close();
Assert.AreEqual(testObject.MySubObject.Id, 3425);

通过关闭会话,然后尝试访问关联的对象,如果未急切加载该对象,则会引发异常。 相反,如果是立即加载,NHibernate 将不会尝试访问数据库,因此不会抛出异常。

How about something like this;

MyObject testObject = new MyObject();
testObject.GetEager("a name");
testObject.Session.Close();
Assert.AreEqual(testObject.MySubObject.Id, 3425);

By closing the session and then attempting to access the associated object if the object is not eagerly loaded it will throw an exception. Conversly if it is eagrly loaded NHibernate won't attempt to access the database and so won't throw the exception.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文