문제

Let's say I open an ISession from the SessionFactory.

For some limited time (not long) this session is alive and used. I fetch entities from the database using this session, and change some of the entities according to some complex business rules. Then I want to save only some of the changed entities.

So, naturally:

        ITransaction t = null;

        try
        {
            t = session.BeginTransaction();

            session.SaveOrUpdate(entity);

            t.Commit();
        }
        catch (Exception ex)
        {
            this.Logger.Error("Transaction failed.", ex);

            if (t != null)
                t.Rollback();

            throw;
        }
        finally
        {
            if (t != null)
                t.Dispose();
        }

However, in accordance with the NH documentation, when transaction commit is called, the session is flushed. This means that all the dirty entities are persisted, even those which I didn't pass to SaveOrUpdate. If some are not in a valid state (e.g. no longer have their not null fk set) everything blows up completely - even if the entities which I tried to save are valid.

Is there a way to tell NH to only save the entity that I give it?

도움이 되었습니까?

해결책

You can call ISession.Evict to remove objects from the session. My memory is that this affects only the object passed as the argument, not the entire object's graph, so changes to child collections are not evicted.

My suspicion is that your unit-of-work is too long. It's unusual to make changes to an entity that you do not want persisted to the database.

Oh, and the SaveOrUpdate call is unnecessary.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top