Reputation: 537
I have the following entity:
public class Item
{
public virtual long ID { get; set; }
public virtual Version Version { get; set;}
More properties...
}
In the entity mapping I have:
ManyToOne(p => p.Version, m =>
{
m.Column("VERSION_ID");
}
The entity Version
is also mapped by code and it's ID is an auto generated sequence.
When I save an Item
, I create a new Version
, assign it to the Version
property and save it. I want to save the Version
entity only after the Item
is successfully saved. Now it throws a TransientObjectException
when I do this. Is it possible to solve this?
Upvotes: 0
Views: 250
Reputation: 563
You cannot save an entity that references a transient object through a mapped property (Item->Version) unless when mapping the property you specify Cascade.Persist or Cascade.All.
Another thing is that since you should be running that code in a transaction the order of inserts should not matter. In case an exception is thrown (or anything else bad happens) after you save Version but before you save the Item, the transaction should be rolled back and nobody is going to see the new version.
The snippet below shows how you can begin/commit a transaction with nHibernate. Notice that the transaction will be rolled back if it does not get commited before it is disposed.
using(var session = sessionFactory.OpenSession())
using(var transaction = session.BeginTransaction())
{
// Do your thing here...
transaction.Commit();
}
Upvotes: 1