nhibernate : how to initialise child list objects

喜夏-厌秋 提交于 2020-01-24 19:25:10

问题


I have the following method in my repository. This works fine, my orderItems are initialised as intended however orderItems contains another collection called OrderItemAddress. These are not initialised. How would i do this?

public Model.Order Get(int id)
{
    using (ISession session = NHibernateHelper.OpenSession())
    {
        Model.Order order = session
            .CreateCriteria(typeof(Model.Order))
            .Add(Restrictions.Eq("Id", id))
            .UniqueResult<Model.Order>();

        NHibernateUtil.Initialize(order.OrderItems);
        return order;
    }
}

回答1:


First of all you might want to issue only one query to the db server using a join, and not initialize the collection after the order is fetched, like this:

public Model.Order Get(int id)
{
    using (ISession session = NHibernateHelper.OpenSession())
    {
        Model.Order order = session
            .CreateCriteria(typeof(Model.Order))
            .Add(Restrictions.Eq("Id", id))
            .SetFetchMode("OrderItems", FetchMode.Join)
            .UniqueResult<Model.Order>();

        return order;
    }
}

Another thing is to eager load a collection of collections without hurting performance wildly. One way to do that in you scenario is this:

var orderCriteria = DetachedCriteria.For<Order>()
    .SetFetchMode("OrderLines", FetchMode.Eager)
    .Add(Restrictions.Eq("Id", orderId));

var orderLinesCriteria = DetachedCriteria.For<OrderLine>()
    .CreateAlias("Order", "order")
    .SetFetchMode("Addresses", FetchMode.Eager)
    .Add(Restrictions.Eq("order.Id", orderId));

IList list = s.CreateMultiCriteria()
    .Add(orderCriteria)
    .Add(orderLinesCriteria)
    .List();

var order = ((IList)list[0]).Cast<Order>().First();

This is unfortunately not tested yet, I am able to do that later. The idea is to make a multiquery that gets all the needed entities in one go (it might not be the most efficient db query possible, but it's at least only one trip) and then let the session stitch up the actual graph from the two result sets.

A slightly different use case is working fine in my current project, but I'm a little unsure if the I have shown here, is completely correct. But I will return on that one :)

EDIT: The above code is changed to something that actually works and is now tested. Sorry for the renaming of the entities and collections. I renamed them slightly for my test project.



来源:https://stackoverflow.com/questions/2841248/nhibernate-how-to-initialise-child-list-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!