views:

390

answers:

2

Hi,

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

+1  A: 

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.

JoshBerke
Thanks for the answer!I was thinking about Evict, but I couldn't figure out how to check if an entity with the same key is there already, so at this point the solution #2 became simpler.I'd add your answer as correct as well, but the system won't let me mark more that one answer..
ulu
+2  A: 

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.

ShaneC
ThanksYes I'm currently considering AutoMapper. Have you ever tried to use it the other way -- dto to entity?
ulu
I have not since it requires .Net 3.5 and we are stuck in 2.0 land but I've heard a lot of good stuff about it so I wouldn't hesitate to use it if I could.
ShaneC