We are trying to combine objects after a StaleObjectStateException has been thrown to save a merged copy.
Here's our environmental situation:
List item
Multi-user system
WPF Desktop application, SQL Server 2008 database
NHibernate 3.1.0.4000, FluentNHibernate 1.2.0.712
Global, long-running NHibernate sessions [for the moment. We understand session-per-presenter is the recommended pattern, but do not have time in our project schedule to convert at present.]
Top-down saves and property navigation (that is to say we save the top-level object (herein called Parent) in our domain graph)
.Cascade.AllDeleteOrphan() used in most cases.
Users exclusively own some objects in the domain graph, but share ownership of the Parent.
Navigation properties on Children objects do not exist.
All classes have numeric ID and numeric Version fields.
Use case:
User 1 starts application and opens Parent.
User 2 starts application and opens Parent.
User 2 adds a child (herein C2).
User 2 saves Parent.
User 1 adds a child (herein C1).
User 1 saves Parent.
User 1 receives a StaleObjectStateException (and rightly so)
We want to gracefully handle the exception.
Because the users share ownership of the parent, User 1 should be able to save successfully, and save the Parent with both his new child, and User 2's child.
When SOSE is thrown, according to Ayende (http://msdn.microsoft.com/en-us/magazine/ee819139.aspx):
your session and its loaded entities are toast, because with NHibernate, an exception thrown
from a session moves that session into an undefined state. You can no longer use that session
or any loaded entities
C1 has already been assigned an ID and Version # by the now-not-useful session. (I wish it had not been.)
How do we combine the use of ISession.Merge() and ISession.Refresh() to get a newly saved Parent that has both C1 and C2 ?
We have tried a number of arcane permutations, none of which fully work.
Usually, either a "row was updated or deleted by another transaction (or unsaved-value mapping was incorrect" or an actual ID collision at the ODBC level.
Our theory, at the moment:
Reset version numbers on C1 (to prevent "unsaved-value mapping was incorrect")
Get a new session
newSession.Refresh(C1);
newParent = newSession.QueryOver[...]
newParent.Add(C1);
newSession.SaveOrUpdate(newParent)
However, all the documentation suggests that newSession.Merge is supposed to be sufficient.
Other posts used as research:
Fluent NHibernate Newbie: Row was updated or deleted by another transaction
Is there an alternative to ISession.Merge() that doesn't throw when using optimistic locking?
StaleObjectstateException row was updated or deleted by
How I can tell NHibernate to save only changed properties
Hibernate (JPA): how to handle StaleObjectStateException when several object has been modified and commited (java, but relevant, i think)
Because the users share ownership of the parent, User 1 should be able to save successfully, and save the Parent with both his new child, and User 2's child.
Why don't you just disable optimistic locking on the child collection? Then anyone can add childs and it won't increase the version of the parent.
Otherwise, here is the solution my current project uses for all recoverable exceptions a session could throw (e.g. connection to DB lost, foreign key violated, ...):
Before calling session.Flush() the session is serialized to a MemoryStream.
If session.Flush() or transaction.Commit() throws an exception that is recoverable, the original session is disposed and the saved one is deserialized.
The calling screen then gets the information that the session was recovered after an exception and calls the same queries again that were called when the screen was opened the first time. And because all the modified entities are still in the recovered session the user now has the state of just before he pressed save.
Related
I am working on a .NET Core Web API which needs to interact using EF Core 5.0.2 with an Azure SQL database.
I have different repository methods where I am interacting with DbContext to add/edit/delete records for different DbSet.
For example:
UserRepository.AddUser(userdata);
Implementation of AddUser is like this,
ourDbContext.UserTable.AddAsync(userdata);
So in user service method, am calling different repository method sequentially and none of those methods call ourDbContext.SaveChangesAsync() individually. A single call to SaveChanges is present after all the repository methods calls which is acting like a unit of work pattern for all the calls as single transaction.
Example:
UserRepository.AddUser(userdata);
ActivityRepository.AddActivity("New User got added");
ourDbContext.SaveChangesAsync();
So my question is: if any saving changes to any of the tables/entities fails, will the previous successful tables change will be rolled back?
For example, suppose this operation
UserRepository.AddUser(userdata);
was successful and the new user record was added to the User table.
But this was not successful:
ActivityRepository.AddActivity("New User got added");
So no activity record was added to the Activity table.
Will SaveChangesAsync() be able to handle this situation automatically and will roll back User table new changes as well?
If not are we supposed to wrap the above codes with transaction scope? Or what is the recommended way to do it.
Briefly how DbContext's Change Tracker works:
You load entities: ChangeTracker remembers current values of all loaded entities (except you use AsNoTracking())
You have modified loaded entities, delete, add new.
You call SaveChanges: ChangeTracker starts searching which objects are changed since last load by comparing with previous values.
DML SQL is generated and everything saved in one SQL statement or in several statements in Transaction.
So, if you have one DbContext for each repository, you do not need to worry about rollbacking, just do not call SaveChanges(). For sure for restart process, you have to recreate DbContext because it contains not needed state.
I have problem with cache in Fluent NHibernate. I want to disable it for query by ID e.g.
session.Get<Person>(10);
Do you have any ideas ?
Are you referring to the first-level (session) cache?
You can refresh the state of an entity from the database by using Refresh, that is:
// Will get the state from the first-level cache if already present in the session:
var entity = Session.Get<EntityType>(entityId);
// Line below will update the entity with the current state from the database:
Session.Refresh(entity);
If you already hold the entity, call directly session.Refresh(person) on it instead of getting it again.
You may also evict it with session.Evict(person), causing it to no more be in the session, and no more tracked for changes either. Then discard it and eventually get it again later if you need.
Otherwise, this is unusual to consider it is a trouble getting it from the session cache. This is frequently a sign of bad session usage, such as using a same session across many user interactions (anti-pattern).
You can still do what Fredy proposes. Or call session.Clear() before getting for clearing the session cache (and losing all pending changes by the way).
Instead of a Person object that is mapped you could create a DTO for Person and do a QueryOver().
The PersonDTO object wont be cached in Nhibernates first-lvl-cache.
I´m using NHibernate to data access Layer.
I have an entity in memory previously loaded, and Im making changes in order to save after on database. The problem comes when my application is running in some machines at the same time, and other user has deleted from database the same object that I have in memory and I want to save. When I try save the changes or delete this entity, a StaleStateException in fired.
I check if an entity exists on database calling session.Get<T> of this way (it´s get a null succesfully):
using (var session = NHibernateSessionHelper.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var entity = session.Get<T>(persistObject.Id);
return entity == null ? false : true;
}
}
The problem comes when I can´t differentiate between when the entity has been deleted by other session/user (therefore my entity in memory is obsolete) or the entity has been recently created and is able to save.
I think that the unique solution is implement a mechanism to check if the entity has already been saved or loaded from database, in order to discard the entity or save when proceed.
Is there a way to check this behaviour by using nhibernate? Im tried with session.Refresh() and session.Get<T> but I still without know if the object is new and ready to save or obsolete.
Help very appreciated.
The situaltion you have is a tipical error handling one. Because a user have dicided to delete an object in your database and an other user want save a change to the same object you can't say what the right state should be. The user is the one who should dicide what to do with situation. You can make your error handling smarter by giving him some chooses. For situations where you have multiple users which write to the same object you should also implement a meganism like optimistic locking to prevent an other user to override a change which he did not see. If you have many of these situation you should think about redesign your db/object structure to edit less data at once or rethink the work/processes your users do with the system.
Using fluent NHibernate I have a property on a class mapped using Version
Version(x => x.Version);
When I save the object, the Version property gets incremented in the database as I would expect, but the value of the property on the object only seems to change sometimes.
using (var tx = session.BeginTransaction())
{
session.Merge(item);
tx.Commit();
item.Version; // Sometimes this is still 1, when I expect it to be 2.
}
The problem is then that if it remains as 1 and I make more changes and save again I get a StaleObjectStateException.
What's weird is that sometimes it works fine and the item.Version value does get correctly incremented, but I can't figure out the difference between the cases where it does and the cases where it doesn't.
I've tried searching but can't seem to find any documentation on this. Can anyone explain what NHibernates expected behaviour is with the Version mapping?
[NHibernate version 2.1.2]
From the ISession.Merge documentation:
Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session.
So, it will not modify item.
(I might add I have never used Merge in my apps. You might want to review how you are dealing with attached and detached entities)
Did you try
item = session.Merge(item);
tx.Commit();
?
You need to flush the session before the updated version will propagate up to your entities. Unless you flush the session, you are responsible for keeping the entities up to date yourself.
You should TYPICALLY let the session flush on its own when its closed. However, in some instances where you rely on database updates that happen via nhibernate and not settings you make to the entity itself, you might need to flush the session yourself after a commit. In this case be aware that when you flush the session ANY entities that are dirty will be committed. This may not be desirable so be sure that the scope is very limited.
What is the difference between SaveOrUpdate and Save/Update in NHibernate. Why wouldnt you just always use SaveOrUpdate? Also, what is the point of SaveOrUpdateCopy?
Chapter 9 covers all of this better than I can:
http://nhibernate.info/doc/nh/en/index.html
But cliff notes:
Save() takes a new object without an identifier and attaches it to the session. The object will be INSERT'd.
Update() takes an existing object that has an identifier but is not in the session and attaches it to the session. The object will be UPDATE'd.
SaveOrUpdate() looks at the identifier and decides what is necessary in the above.
SaveOrUpdateCopy() is special in that say you have two objects with the same identifier -- one in the session and one not. If you try and update the one not in the session an exception is thrown normally (you are now trying to attach two objects that represent the same persistent object to the session). SaveOrUpdateCopy() copies the non-session object state to the session object state.
I'm not sure how you are going to use NH, but for a lot of cases all you need is Save(). The session is doing ALL of the work necessary to know what has to be updated and simply Flush() or a Commit() does everything you need.