Reputation: 3491
I have two Person and PersonDTO classes and I'm using NHibernate to save these objects. As while as I have One user there is no problem and as soon as another user is going to update the object that another user is updating it. then Both of the can update the same object and because it is updated by another user, on of the changes will lost.
In order to implement cuncurrency I used two ways that both of them faced with problem.
The first approach is working great with any problem but unfortunately I don't have enough permition to the Load Person completetly with its dependencies. so that I have to use the second approach.
In the second approach when I set (update) Version it is o up to the last second, but NHibernate is using its old Version so that my changes won't apply.
Look at the following Code
load a Person by ID
person = locator.PersonRepository.GetById(dto.Id);
Version field is loaded by new value. but I need to set it from my PersonDTO object
person.Version = dto.Version
During update process NHibernate passes old value to sql and I don't face with concurreny error.
What should I do to implement concurrency in this way. Any help is appriciated.
Upvotes: 2
Views: 1557
Reputation: 1366
Your code should be like following
class
public class Person
{
public virtual DateTime Version { get; set; }
public virtual string FirstName { get; set; }
.
}
Map Person.version property as version field on Mapping file.
<version name="Version" column="Version" type="timestamp" unsaved-value="1/1/0001" />
and update code like following
var person = session.Get(personDto.Id);
person.Version = personDto.Version
person.FirstName = personDto.FirstName
session.SaveOrUpdate(person);
Once you enable show sql and run it, you should see like following
UPDATE [Person]
SET Version = @p0, FirstName = @p1
WHERE PersonId = @p3 AND Version = @p4;
Upvotes: 1
Reputation: 12610
As I understand your problem, I guess You have a field that its getter works fine but when you are trying to set it you face with problem, if it is so, then check the following considerations
provide more information if these ideas didn't help you
Upvotes: 1
Reputation: 42227
Ayende has an interesting article on the different types of concurrency supported by nHibernate. If you setup a version column then nHibernate will manage the value of the version automatically and throw a StaleObjectException
when you try to update an object that has become stale.
You can use this exception to notify the user or implement a more complicated automatic concurrency resolution method.
Upvotes: 2