Fluent NHibernate Newbie: Row was updated or delet

2019-06-06 04:09发布

问题:

I'm in the early stages of building out a database with Fluent NHibernate. I implemented a unit-of-work pattern in ASP.NET MVC 3 to let NHibernate update my database schema for me. To insert/update my initial data, I have a Database controller with an Update action that tries to SaveOrUpdate(...) a User entity (the administrator user) into the Users table.

After manually deleting all user records via Visual Studio and re-running my Update action to repopulate the Users table, I receive the following NHibernate.StaleObjectStateException exception:

Row was updated or deleted by another transaction (or unsaved-value mapping was
incorrect): [Invoicer.Data.Entities.User#3105248d-ca91-4c64-bf8f-9ebb017943b7]

Line 26:        {
Line 27:            if (_transaction.IsActive)
Line 28:                _transaction.Commit();
Line 29:        }

Note: the saved or updated user ID is a Guid with the value above (3105...).

What am I doing wrong?

回答1:

Solved with Mapping

NHibernate was assigning User IDs (Guid) for me using the Guid comb method. Manually specifying the ID was tripping up the mapping. I prefer to assign these IDs myself, so I changed the User entity ID mapping to be manually assigned in my UserMap class:

Id(x => x.Id).GeneratedBy.Assigned();


回答2:

This error also occurs when the changed context and you if you PK is character.

The Solution is apply Trim() in PK when Update(data, data.code.Trim());