Filter child collection returned with Aggregate Root using Nhibernate

。_饼干妹妹 提交于 2019-12-30 10:00:20

问题


I'm trying filter the child collection of an aggregate root when loading it with Nhibernate. Load a Customer with all their Orders that have been shipped. Is this possible?


回答1:


Well, you can expose properties that are filtered in the map, like so:

<bag name="shippedOrders" ... where="Status == 'Shipped'" >
   <key column="CustomerId" />
   <one-to-many class="Order" />
</bag>

The 'where' attribute is arbitrary SQL.

Theoretically you could have two properties of Customer, Orders and ShippedOrders. However, I should say that I have not done this, and I would want to test how NH handles cascading in this case. In any case, you will have to take care when new items are added/removed that they are added/removed correctly to both collections.

The fact that you want to do this makes we wonder if Order is an aggregate root. It might be less trouble in the long run doing it like this:

orderRepository.GetOrders(int customerId, OrderStatus[] statuses)



回答2:


You could look at it the other way - load all the shipped orders for a Customer.

session.CreateCriteria( typeOf(Order) )
    .Add( Restrictions.Eq("Shipped", shippedStatus ) )
    .Add( Restrictions.Eq("Customer", requiredCustomer) )
    .List<Order>();



回答3:


You can also do it using HQL using session.Filter(customer.Orders, "where this.Status == 'Shipped'");




回答4:


ICriteria crit = session.CreateCriteria (typeof(Customer));

crit.CreateAlias ("Orders", "o");
crit.Add (Expression.Eq ("o.Status", shippedStatus));
crit.Add (Expression.Eq ("Id", customerId));

return crit.UniqueResult <Customer>();

something like that.



来源:https://stackoverflow.com/questions/247571/filter-child-collection-returned-with-aggregate-root-using-nhibernate

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