Torkel
Torkel

Reputation: 3404

Version does not increment when updating child item

If I read the documentation correctly if I have an Order entity mapped with a version column (incremented by nhibernate) then changes to orderlines should update the version number for the aggregate root (the Order). It does indeed do this when I add/remove orderlines, but if I only change, for example the quantity on an orderline the version of the order is not updated. Is this expected behavior?

I checked the NH source and it appears it only checks for dirty collections when trying to determine if version increment is necessary, and the collection will only be dirty when adding/removing items, not if any item in the collection is dirty.

I have the following mapping:

public class OrderMap : ClassMap<Order>
{
    public OrderMap()
    {
        Id(c => c.Id).GeneratedBy.GuidComb();
        Version(c => c.Version);
        OptimisticLock.Version();
        HasMany(x => x.OrderLines)
            .Inverse()
            .Cascade.AllDeleteOrphan();
    }
}

public class OrderLineMap : ClassMap<OrderLine>
{
    public OrderLineMap()
    {
        Id(x => x.Id).GeneratedBy.GuidComb();
        Map(x => x.Quantity);
        References(x => x.Order);
    }
}

So my question is if this is expected behavior? That is that version will not update when modifying child entities only when the child collection is modified with remove/add. It sort of breaks the aggregate root concurrency model.

Upvotes: 5

Views: 1449

Answers (1)

Torkel
Torkel

Reputation: 3404

This is indeed expected behavior. There is a way to solve it using a event listener that can detect changes in children and traverse to the aggregate root and lock that optimistically (triggering a version change).

More information in this post by Ayende: http://ayende.com/blog/4055/nhibernate-automatic-change-tracking-for-aggregate-roots-in-ddd-scenarios

Upvotes: 4

Related Questions