tags:

views:

32

answers:

3

Hi there,

I was wondering if there is actually an existing way to work out if an object is persisted yet or not? For instance an IsPersisted(object obj) method...

Checking the identifier for an empty value would work I'm sure, but I haven't fully thought this through and just wanted to be sure there wasn't something I was missing.

Thanks,

Tony

+2  A: 

Checking the id against the unsaved-value is a good way. That's what the session.SaveOrUpdate method uses to decide whether to emit an INSERT or UPDATE statement.

Darin Dimitrov
+1  A: 

NHibernate potentially looks at three different properties to see if an entity is persisted. In most cases checking the Id against the unsaved-value is sufficient. If the Id is assigned, a Version or Timestamp property will be checked.

  1. Id - this works if the id is not assigned.
  2. Version - if present and if the id is assigned.
  3. Timestamp - if present and if the id is assigned.
g .
A: 

This is the entity persister's responsibility, so I'd let it figure it out instead of manually checking the unsaved-value:

public bool? IsPersisted(object obj, ISession session)
{
    var sessionFactoryImpl = (ISessionFactoryImplementor)session.SessionFactory;
    var persister = new SessionFactoryHelper(sessionFactoryImpl).RequireClassPersister(obj.GetType().AssemblyQualifiedName);
    return !persister.IsTransient(obj, (ISessionImplementor)session);
}

The entity persister does a few more things than just checking the unsaved-value, like checking the version and the second-level cache. And it seems that it's not always possible to find out if it's transient (it returns bool?).

Mauricio Scheffer