NHibernate: Is there a way to work out if an object is persisted or not?

0 votes
asked Sep 18, 2010 by tony-day

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.



4 Answers

0 votes
answered Sep 18, 2010 by darin-dimitrov

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.

0 votes
answered Sep 18, 2010 by g

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.
0 votes
answered Sep 18, 2010 by mauricio-scheffer

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?).

0 votes
answered Sep 15, 2017 by michael

I wrote the following ISession extension, which seems to work. If you've got something better, I'd be happy to see it.

    public static bool IsNewEntity(this ISession session, object entity)
        if (entity == null) return false;

        ISessionImplementor sessionImpl = session.GetSessionImplementation();
        IPersistenceContext persistenceContext = sessionImpl.PersistenceContext;
        EntityEntry oldEntry = persistenceContext.GetEntry(entity);

        return oldEntry == null;
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter