.netnhibernatefluent-nhibernaterepositoryrepository-pattern

NHibernate: Is it okay to manipulate the repository directly from my entity classes?


I have a custom repository implementation using NHibernate through Fluent NHibernate's AutoPersistenceModel.

I have a bunch of entity classes which I persist with this repository.

The question is, is it okay to put real business logic inside these entity classes?

Is it still okay if some of this business logic requires to manipulate the repository itself? (Eg. some methods would need to create some new entities, some of them need to update existing entities, etc.)

I know NHibernate has powerful persistence ignorance features, but I'm still not sure about this detail.


Solution

  • Logic w.r.t Entities should be restricted to it's "business domain". It is a very bad idea/design to update other entities / infrastructure within an entity.

    i.e.

    Order --> OrderLines
    Order {OrderId, OrderDate, Customer, OrderLines, ...}
    OrderLines {OrderLineId, Order, Item, Price, Quantity, Deliveries, DeliveredQuantity, ...}
    
    OrderDelivery --> OrderDeliveryLines
    OrderDelivery {OrderDeliveryId, Customer, DeliveryDate, ...}
    OrderDeliveryLines {OrderDeliveryLineId, OrderDelivery, OrderLine, DeliveryQuantity, ....}
    

    Where orderLine's delivered quantity is a summation of all deliveries made against it.

    Thus in the case above it would be wrong to create/update a delivery via a Order (i.e. order process), Delivery's deliveryLine is to be made against a corresponding orderLine w.r.t delivered qty(within a delivery process).

    When transactional boundaries are clearly defined, you will never require the process logic to creep into your "business domain"

    http://domaindrivendesign.org/