I have a Car in DB where Model field is "Ferrari"
using (new TransactionScope())
{
var car = Find(1);
car.Model = "Ferrari Plus";
// i need the old Car value to make a comparison
var car2 = Find(1);
// i need here the db Car record, instead i have the cached Nhibernate value
if (car2.Model == 'Ferrari")
// do something
}
i modified the code in this way
using (new TransactionScope())
{
var car = Find(1);
car.Model = "Ferrari Plus";
// i need the old Car value to make a comparison
using (new TransactionScope())
{
var car2 = Find(1);
// i got the db value buuuuuuut
// if i save because i need to save the modific Car i got an error
if (car2.Model == 'Ferrari")
car.Save(); // ERROR: 2 objects with the same id exists
}
}
how can i avoid this problem? How can i get 2 versions of the same object into the same NHibernate Session?
One of the base principles of nhibernate is to not have 2 objects that are the same in the same session. What you are asking cannot be done as far as I know.
You could query car
in one session close the session. Query car2
in another session and do your compare against the two objects. Update car2
with car
's properties.
Do the same as above except don't copy the values from car
to car2
. Instead you would open another session and do a session.Update(car);
You could do is to create a copy of the original or create a dto. When you do your comparison compare the persistent instance (changed copy) to the copy/dto.