Search code examples
nhibernatedto

NHibernate, DTOs and NonUniqueObjectException


We're using the DTO pattern to marshal our domain objects from the service layer into our repository, and then down to the database via NHibernate.

I've run into an issue whereby I pull a DTO out of the repository (e.g. CustomerDTO) and then convert it into the domain object (Customer) in my service layer. I then try and save a new object back (e.g. SalesOrder) which contains the same Customer object. This is in turn converted to a SalesOrderDTO (and CustomerDTO) for pushing into the repository.

NHibernate does not like this- it complains that the CustomerDTO is a duplicate record. I'm assuming that this is because it pulled out the first CustomerDTO in the same session and because the returning has been converted back and forth it cannot recognise this as the same object.

Am I stuck here or is there a way around this?

Thanks

James


Solution

  • You can re-attach an object to a session in NHibernate by using Lock - e.g.

    _session.Lock(myDetachedObject, NHibernate.LockMode.None);
    

    which may or may not help depending on exactly what is happening here. On a side note, using DTO's with NHibernate is not the most common practice, the fact that NHibernate (mostly) supports persistence ignorance means that typically DTO's aren't as widely used as with some other ORM frameworks.