0
votes

What's the recommended way of updating an entity? So far, I figured out two ways:

  1. Just create a new entity with the existing Id and updated property values, and use session.SaveOrUpdate()
  2. Use a DTO, retrieve the existing entity using session.Load(dto.Id), assign new vaues from the dto, then save.

No1 requires much less effort, but sometimes I'm getting an exception: "a different object with the same identifier value was already associated with the session". Is there a simple way around that?

No2 might require an extra trip to the DB I guess?

Sorry if that's been answered already, just couldn't find the answer.

Thanks ulu

2

2 Answers

2
votes

Your second option with DTOs is my preferred way. Your DTOs should be specific to the screen (Google Screen Bound DTOs) so that the screen and your domain can change independently of one another.

It also won't add an extra trip to the db since #1 would require a disconnected entity which would have to be reconnected (which triggers a select) after the fact. Worrying about one extra select also smells strongly of premature optimization.

In terms of converting from domain to DTO I'd recommend looking at AutoMapper.

1
votes

To use No1 you could try and Evict the object from nHibernates session. This will get rid of the error about the object already being in the session.

I would recommend approach number 2. Especially if you want to add any sort of optomistic locking. In many cases a single extra hit to the db won't be that expensive.

Edit

To check if a entity already exists in the session you can use the Contains(obj) method on the Session instance.